14 ms·
A guide to better embedded C++
- berti 9y agoNothing in the presented article that can't be done just as (or more) easily in C. The article really just presents the absolute basics from an intro embedded systems class.
- minipci1321 9y agoyes, I somehow expected to see something like Kvasir: https://github.com/kvasir-io/Kvasir https://github.com/kvasir-io/Kvasir
- tcbawo 9y agoI was surprised not to see anything about RAII techniques (http://en.cppreference.com/w/cpp/language/raii http://en.cppreference.com/w/cpp/language/raii). Tightly-managing resources via object lifecycle is probably one of the killer features that C++ brings to embedded.
- taneq 9y agoOften in embedded systems, it's actually less of an issue, because you don't need to "acquire" resources - you have the run of the hardware and you're not sharing any devices with any other code. Likewise, you don't need to keep memory free for other applications to use, so there's a strong tendency to just allocate everything statically. It's simpler and more reliable.
- stevenhuang 9y agoIn a lot of embedded systems, the penalties associated with RAII and other runtime goodies like vtables are often prohibitive, so they're commonly disabled. It's a factor in why C continues to be the lingua franca instead of C++ in the embedded space--it's simpler and still "good enough" not to warrant a switch-over to C++ (in addition to many other reasons). The compile-time features of C++ are a great reason to switch over though, and for devices with greater resources, C++ becomes an even better fit.
- Gibbon1 9y ago> and for devices with greater resources, C++ becomes an even better fit. It doesn't take having much more resources before switching away from C++ is a vastly better option though.
- jcelerier 9y ago> the penalties associated with RAII and .... there are 0 penalties associated with RAII. struct my_interrupt { my_interrupt() { vendor_specific_horrible_stuff(0x237ABC); } ~my_interrupt() { if(whatever) vendor_specific_horrible_stuff(0x237BAC); } }; void f() { my_interrupt is_enabled; // do stuff } will translate to exactly the same assembly than void f() { vendor_specific_horrible_stuff(0x237ABC); // do stuff if(whatever) vendor_specific_horrible_stuff(0x237BAC); }
- proverbialbunny 9y agoSpeed is not the issue for embedded development. The problem with C++ is it has a few language features that are not deterministic making standard C++ not ideal for real time code. Most of the stl uses these features, so most vanilla C++ is disabled for many embedded environments. Also, there is a push for C++23 to have deterministic exception handling. If this passes (and it likely will) most of the stl will become available for embedded, and when that time comes C++ is going to become far more of a viable option than it currently is. If you're curious you can read about it here: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0709r0.pdf http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p070...
- jhack 9y agoThe author says setting a register like this is hard to read and maintain: *(volatile std::uint32_t*)reg_name = val; And the author's solution is to replace that one line with this: struct DeviceSetup { enum class TableType : std::uint32_t { inphase = 0, quadrature, table }; std::uint32_t input_source : 8; TableType table_type : 4; std::uint32_t reserved : 20; }; volatile auto device_registers_ptr = reinterpret_cast<DeviceSetup*>(DeviceControlAddress); I'm not really seeing the readability and maintainability advantages here.
- tropo 9y agoBoth methods are buggy, but the second is also needlessly complicated. The first possible bug is aliasing. The type of reg_name and DeviceControlAddress are not given, so it is possible there isn't a bug. The second bug relates to memory ordering. Adding "volatile" will tell the compiler to do things in order, but the compiler will not pass that requirement on to the CPU. The CPU itself may reorder things. I saw this affect an embedded system back in 1998, and the problem has only become more common in the 2 decades since. Generally you will need assembly code to avoid the bug.
- viraptor 9y ago> The CPU itself may reorder things. > Generally you will need assembly code to avoid the bug. What do you mean by this? Compiler outputs binary code the same way assembler does. If the CPU reorders your instructions, it will happen in both cases. If there are some specific instructions which create memory/reordering barriers, they can be expressed in higher level languages as well.
- monocasa 9y agoA lot of times they aren't barriers, but metadata on the address map. ARM sticks it in the page tables, and x86 sticks it in the MTRRs. PowerPC does treat it like a memory barrier instruction (eieio - Enforce Inorder Execution of I/O), but that's a stronger guarantee than you'd want for all volatile accesses.
- AceJohnny2 9y ago> Embedded is a wonderful versatile world which allows developers to create various interesting everyday devices (in collaboration with the hardware team). ROFL! I've been working in embedded for over a decade, and it's always quagmire of buggy hardware patched over with C code, half of whose programmers have actually transitioned over from hardware design and don't know what they're doing. With that in mind, I'm going to assume the author was sarcastic. I love the field, for getting to work deep inside and very early on bleeding-edge hardware, but by god most days feel like being in the coal mine of computer systems.
- keithnz 9y agoI've done embedded stuff for 25+ years. I find that it's always far better to stick with simple C code. Because it's the native language of the embedded world. It has a lot of good advice on how to write robust code. If needed, layer something like lua on top, but for the most, stick with simple C and proven embedded techniques. The article mentions a HAL. That's definitely a must. But don't get too fancy with trying to do that. Do I keep wanting to use something else? yes. Am I fan of C? No. Is my embedded device really just a scaled down PC with an OS and a MMU and good amounts of memory? use what ever language you want. Rust is promising, but will never be a good option on low level devices. I have seen some nice stuff done with Forth
- Narishma 9y ago> Rust is promising, but will never be a good option on low level devices. Why not?
- kabdib 9y agoThe last low-level device I shipped code on, we had 2K of program space and about 1K of RAM. Started writing in vanilla C, crunching pieces into hand-written assembly and rewriting fat code when space got tight. 6 bytes free in the final code. I might be going out on a limb when I claim that Rust won't touch this kind of system . . . but probably not. The system before that was largely just a USB driver, an event loop and some interrupt handlers, supporting a large amount of ported-over and mostly already existing stuff in C that did the interesting and product-defining algorithmic heavy lifting. I guess that we could have written the infrastructure in Rust, but it's hard to see the win in using two languages (the algorithmic stuff was not going to get a rewrite). Rust isn't great for other reasons, too. Finding good embedded systems programmers is hard enough; require something bleeding edge like Rust and the population of candidates plummets to "well, we might be able to find and hire one person this year" territory.
- AceJohnny2 9y ago> Unfortunately, a lot of embedded low-level libraries deal with registers this way: *(volatile std::uint32_t*)reg_name = val; Who still writes code like this!? (maybe the ST folks responsible for the CubeMX BSP for STM32. Ugh...) Most places have finally moved on to using structs and bitfields. GCC and Clang support them well and consistently on the various architectures I've worked on (MIPS, some weird DSP, and a slew of ARM variations). Some proper C code will define the 32-bit register like this (usually in a header provided by the hardware vendor, generated from the HDL): typedef union some_reg { uint32_t raw; struct { uint32_t bits1:4; uint32_t bits2:3; uint32_t rsvd:5; uint32_t bits2:20; } } some_reg_t; Then use it either like: some_reg_t reg; reg->raw = READ_REG(reg_addr); reg->bits1 = 4; WRITE_REG(reg_addr, reg->raw); Or: volatile some_reg_t *reg = (some_reg_t*)reg_addr; reg->bits1 = 4; The latter assumes the register address is mappable, and that programmers are aware that writing the field performs a Read-Modify-Write of the whole register. Programmers being fallible, it's a more risky approach that I don't see often, despite how concise it is.
- kbumsik 9y ago> Who still writes code like this!? Believe or not, a majority number of ARM MCU vendors does that with CMSIS headers in my experience (ST, TI, NXP, Nordic, EFM32...). To be more precise, the registers are accessed using mask and shift macros. I've work on many ARMs too but only Atmel's header files use struct bitfield you mentioned. But yeah, I've also seen that most of non-ARM vendors use struct bitfield.
- AceJohnny2 9y agoHm, is armcc still a thing? I don't remember what it guaranteed (or not) for bitfields. If it doesn't work consistently, that would explain that they're using masks and shifts. That, and because the C standard leaves it implementation-defined.
- monocasa 9y agoThe ARM ABI defines a lot of useful semantics for bitfields (particularly when combined with volatile), but GCC perennially regresses and breaks them so next to no one uses them.
- bigcheesegs 9y ago> N.B. Accessing registers modified by the hardware may be treated as a multi-threaded application. Therefore, it is worth considering using std::atomic<T> instead of volatile T. This is incorrect. Compilers are allowed to reorder and combine atomics as long as they follow the rules. See: https://github.com/jfbastien/no-sane-compiler https://github.com/jfbastien/no-sane-compiler
- tripletao 9y agoIf I understand correctly, that makes the article grossly wrong. Like, if you have a serial port transmit register and execute SERIAL_TX_DATA = 0x01; SERIAL_TX_DATA = 0x02; to enqueue two bytes to transmit, then the compiler is allowed to skip the first write entirely.
- Gibbon1 9y agoA naive implementation of the SERIAL_TX_DATA macro will totally give you behavior like that.
- tripletao 9y ago#define SERIAL_TX_DATA (*((volatile uint32_t *)<addr>)) is pretty naive, and correct. The article's advice seems not to be.
- Gibbon1 9y agoFriend smarter than me ran into a bug where when DMA was active on a multi-core uP you needed to do a read op between two writes to a IO address or the first write wouldn't happen. I think on an ARM processor if it's normal memory you can't guarantee ordering. But ARM supports a device memory type which disables caching and reordering memory accesses by the hardware.
- tripletao 9y agoI think ARM's "strongly-ordered memory" concept is supposed to solve this? Was your friend's problem intended behavior, or a silicon bug? http://infocenter.arm.com/help/topic/com.arm.doc.dai0321a/DAI0321A_programming_guide_memory_barriers_for_m_profile.pdf http://infocenter.arm.com/help/topic/com.arm.doc.dai0321a/DA...
- 95014_refugee 9y agoAlmost nobody in their right mind would do this. (To be fair, many people working with hardware are not in their right mind anymore. Try it, you'll see.) 1: Don't use bitfields when interacting with registers. The language does not guarantee the behavior you want. Or even the behaviour you think you want. 2: 'volatile' is the contract that we (language users) have hammered out with the compiler industry over the last 20 years; it means "don't get smart with this memory location". Use it. 3: For any SoC of more than trivial complexity, the vendor will supply headers that describe the hardware (register names and addresses, field names, sizes, offsets, enumerations, etc.). You will hate their naming convention. You will hate the way they encode field sizes, offsets, masks, etc. Deal. Because the alternative is you, or your intern, making dozens of mistakes attempting to transcribe from the documentation. Here's a hint - the better vendors auto-generate these headers from the VHDL. They are often right even when the documentation isn't. 4: It's trivial to template most interactions with registers. See, for example: https://github.com/steffanw/laks https://github.com/steffanw/laks 5: A little investment in your abstractions, even if the lower levels look a bit more complex or verbose, helps make your application logic easier to follow. The discussion here about re-ordering is largely moot; if you're having issues with the core re-ordering your transactions, either your core is børked or you haven't mapped your peripheral space correctly. The former is pleasantly rare, the latter common enough that your compiler vendor is going to ask you about it before they give you a bug number.
- minipci1321 9y ago> Here's a hint - the better vendors auto-generate these headers from the VHDL. Yes! And the hateful naming might come straight from the RTL where digital designers have their own notions about what is a pretty name ;-) > They are often right even when the documentation isn't. More so -- if you decide for changing these names, one day debugging a complex issue will require talking to RTL people and everybody will be instantly lost -- your names won't be meaning much to them.
- stevenhuang 9y agoChoosing between bitfields and masks for register twiddling was something I looked into deeply. Like the article, I wanted the readability of bitfields, but after reading about all the pitfalls and how loosely bitfields specs were defined in the C89 standard, I decided to go with masks instead. Here was a great summary I found from a comment explaining the dangers of bitfields. Seeing it spelled out like this made it clear which to choose, lest you're a fan of nasal demons :). "The royal mistake is to use bit fields in the first place. The following is not specified by the standard: – whether bit field int is treated as signed or unsigned int – the bit order (lsb is where?) – whether the bit field can reach past the memory alignment of the CPU or not – the alignment of non-bit field members of the struct – the memory alignment of bit fields (to the left or to the right?) – the endianess of bit fields larger than one byte – whether plain int values assigned to them are interpreted as signed or unsigned – how bit fields are promoted implicitly by the integer promotions – whether signed bit fields are one’s compliment or two’s compliment – padding bytes – padding bits – values of padding bits. – and so on." Source: https://embeddedgurus.com/stack-overflow/2009/10/effective-c-tip-6-creating-a-flags-variable/#comment-2390 https://embeddedgurus.com/stack-overflow/2009/10/effective-c...
- tripletao 9y agoSo maybe everyone but me knows this, but what's the behavior of bitfields on the bus? Like, if r.x is the bottom 6 bits of a 32-bit register, then does the compiler generate an 8-bit access or a 32-bit access? What if it's bits 13 through 18? An unaligned 16-bit access? Two 8-bit? A 32-bit? Where is this specified? Depending how your peripheral is implemented, this absolutely can matter. Nothing stops you from building devices where the low byte of *((uint32_t *)x) doesn't work like *((uint8_t *)x) and people do. I always just code the 32-bit access and pull the bits out myself, because I know what will happen. This is even before considering stuff like a GPIO output implemented with two write-only registers, where 0 leaves the bit unchanged and 1 sets/clears it. The result of layering a bitfield on that does not seem intuitive to me. The article also says that you should build abstraction layers for your peripherals, instead of making all your code write to registers everywhere. That seems (a) pretty well-settled as true, and (b) entirely independent of whether you do the register accesses with bitfields or explicit shifts and masks.
- JoachimSchipper 9y agoYes, what bitfields do on the bus is very undefined. Admittedly, a compiler is free to implement a dereference of uint32_t by loading four separate bytes, too, hence the imprecise "very undefined" in the first line...
- tripletao 9y agoI just tried this with IAR for Cortex-M3. I didn't check thoroughly, but so far it looks like right-aligned bitfields of eight bits or less generate an LDRB (8-bit). All other bitfields generate an LDR (32-bit), even if they lie entirely within a byte. I see the makings of a fun trick to play on a colleague. I don't see anything I'd be too inclined to use in production code.
- orbifold 9y agoThis is a problem I encountered just recently, even if your bus might in principle support byte wise access to memory, it might be the case that one of the custom devices on that bus simply ignore that feature, leading to surprising and unpredictable results.
- mschwaig 9y agoI picked C over C++ in an quasi-embedded environment given we would have a team with highly variable C/C++ skills. I was worried people would get too fancy with C++. Probably it would have been fine if we would have taken away most of the language. It turns out the problem with C in that setting was that good C code seems to require a lot of ceremony and conventions for things like error handling and modularity. I hope that Zig (https://ziglang.org https://ziglang.org) will become a viable alternative in that space. It's quite a small language, more comparable to C than to C++ or Rust. It's meant to result in similar LLVM bitcode as well-written C, while being highly compatible with C and and giving you some extra safety guarantess over C as well.
- youdontknowtho 9y agoHelp me out... Why not use a C or Algol derivative syntax?
- mschwaig 9y agoI think the syntax is not too far off from C. I am not affiliated with the project, only supporing it on Patreon, so I cannot speak about the designer's intentions with Zig specifically. Generally in language design, if something works the same way as in other languages, that's great. You can re-use the keywords/syntax and build on peoples prior knowledge. However if you have some feature that actually works quite a bit differently from other languages the syntax should probably be different. Otherwise people might feel at home right away on a superficial level, but actually get bitten by the surprising ways in which the new thing works differently to the one they are used to later.
- Khoth 9y agoI'm not a fan of anything that writes to a register just by assigning a value to some variable. I much prefer having some kind of READ_REG/WRITE_REG inline function (or macro at a pinch). Sooner or later you're going to find yourself wanting to log all register accesses, or run the firmware against a model of the hardware, or something, and when you do it's a great help to have to handle it in only one place.
- youdontknowtho 9y agoIt would be great if everyone who knows better than the author would write articles instead of just critiquing them. I'm not trying to be facetious. It would be awesome if more of the advanced developers here would write things like this and share their knowledge.
- otempomores 9y agoAt least its not androids.. We got the features.. God have mercy on performance and battery if you use them.
- yason 9y agoThe article could do without any references to C++. Surely writing long, imperative lists of register writes makes the reader's mind boggle. C has more than enough tools to encode all that into something that is maintainable and readable. Because if you just take C++ to implement some handy, convenient constructs you also invite the closet full of demons that come with the language. And quite frankly the abstractions given in the article are quite trivial. Any decent programmer would create similar abstractions as a part of normal course of work because decent programmers know they are forgetful and they want to spend their modest number of brain cycles on the higher levels of thinking instead.
- billforsternz 9y agoSuperb comment. Good programming is about building effective layers of abstraction. Bit twiddling is fine, but encapsulate it. Mass setting of registers should be presented as a readable table (possibly an instantiated structure) with no special executable code in sight.