9 ms·
C++ on Embedded Systems
- zwieback 10y agoNice article! I was doing C++ for device drivers in the early 90s and my advice back then was more or less the same. Open source toolchains didn't really exist back then, at least on the PC, so some stuff was harder to achieve.
- shortoncash 10y agoThis was an enjoyable article. Is it necessary to call the constructors in the manner specified in the article? What would be the problem with using placement new in a designated block of memory?
- mrkline 10y agoThe approach I laid out makes sure that the constructors for all of your global/static objects get called. AFAIK, there's no reason you couldn't do everything "by hand", but it seems like a lot more work for questionable gain.
- shortoncash 10y agoValid point. However, there's no reason it has to be overly manual. As an example, you can make all the global object classes mixins for a variadic and use a variadic constructor and member methods to bring them all online in one fell swoop, even parameterizing construction via policy classes as template parameters. (Plus you have the added benefit of knowing via sizeof() on the variadic type the footprint of all the global objects.) The gain would be to avoid the dependence on the linker script solution, particularly if tweaking linker scripts on a different compiler/build environments.
- Espressosaurus 10y agoI prefer forcing a top-down initialization using placement new for any extent globals, that way initialization order can be carefully controlled. E.g. the OS gets started before we even bother bringing anything else up, other initialization happens in a separate task, then worker tasks are brought up, etc. Everything is sequenced, and we don't have to go to the linker script to figure out what's actually getting called. Since the globals are singletons, any attempt to get their instance when they've already initialized is an error that will blow the program up. Helps keep us honest.
- keithnz 10y agoEmbedded Systems are quite varied these days. The one in the article sounds more at the high end of the scale. In more resource constrained environments, C is still the king. ( though I'd prefer something far more robust than C that works well on resource constrained platforms and cross compiles to ansi C ). I think once your system is large enough, C++ is not your only option, many languages can be used.
- hellofunk 10y agoI've always read that there is no reason C++ cannot be used in any environment where C is used, assuming the compiler exists. There is nothing about C++ that makes it less resource-sensitive than C, and in fact with C++14 there is a tremendous amount of computation (including some instance methods!) that can be done at compile time! Scott Meyers shows some of this in his presentation at various conferences on embedded systems. It really opened my eyes to how useful templates can be in tight systems, and those don't exist in C.
- sjolsen 10y agoTo expand on this, C++ fundamentally uses the same machine model as C (or at least one that's very, very close). Where C++ differs from C is the array of high-level language constructs, which map down to that common machine model (this is what is meant by "zero-cost abstractions"). The idea is that when you use a construct like templates or virtual functions, what it compiles down to is not significantly different from the analogous code you would write in C (hand-duplicated routines with different concrete types and structs-of-function-pointers, resp.). There are exceptions (no pun intended) to this, namely exceptions, RTTI, global construction/destruction, and the intricacies of new/delete. As the article points out (as will anyone who advocates the use of C++ in constrained environments), none of these are really necessary to use C++ effectively and can be safely stubbed out.
- deleted 10y ago[deleted]
- fest 10y ago
- fest 10y agoAwesome guide on how to get the best out of C++ on embedded systems. One thing I would add is: enable all the warnings you can and make them errors: "-Wall -Wextra -Wpedantic -Werror". I know it's hard to do in practice (who will want to fix the thousands of warnings in a well seasoned codebase?) but it's a good idea for new projects. Especially if team uses the same compiler (sometimes the code produces warning with newer gcc versions).
- jackhack 10y agoYes! This was a practice beat into me (not literally, but close) at my first programming gig in the 1980s. "A compile should not produce warnings! If the code producing the warning is truly intentional & deliberate, then grab a senior developer to review and ONLY if he agrees we'll issue a #pragma directive to tell the compiler to ignore it. But most of the time, (99%+) there's a way to do what you want without triggering a warning." Most of the time it was simple mistakes or laziness like a downcast conversion leading to loss of precision, etc. but occasionally on review we'd find somethign really stupid/dangerous like type mismatches on a pointer ("well, no, that index into a string should NOT be used to reference memory...") or a return before a free() call (memory leak), uninitialized values (yay for random behavior!). I thought sloppy, warning-riddled code was ancient history until last week, when I did a fresh install of R Studio on a server + a couple dozen packages, watching page after page of gcc compiler warnings scroll past.
- pjmlp 10y ago> I thought sloppy, warning-riddled code was ancient history until last week, when I did a fresh install of R Studio on a server + a couple dozen packages, watching page after page of gcc compiler warnings scroll past. Nah, just compile or use any Gtk+ based application.
- wott 10y agoOh yes, that is true. I launch every program from terminals and a terrible warning parade fills my terminals whenever it is a Gtk application. I came to think that the developers never actually launch their program this way and never the see the flow of warnings they trigger.
- deleted 10y ago[deleted]
- benhoyt 10y agoA few years ago I wrote an article entitle "Should you use C++ for an embedded project": http://blog.brush.co.nz/2011/01/cpp-embedded/ http://blog.brush.co.nz/2011/01/cpp-embedded/ -- however, my embedded experience is mostly on very small micros, like less than 256KB flash and 64KB RAM. In those cases, I'd still very much lean towards the explicitness and simplicity of C. For less resource-constrained systems, C++ would be reasonable.
- pvaibhav2 10y agoI regularly write C++14 on cortex-m0 with 4 to 16KB RAM.
- brandmeyer 10y agoI find that -ffreestanding is too limiting in the presence of a decent C library. If newlib and libsupc++ are available, then you probably don't want -ffreestanding. Instead, provide your own syscalls and rely on the linker to tell you when you've inadvertently pulled in something extra heavy.
- KKKKkkkk1 10y agoThere is a tax that you pay by introducing C++, and that is chasing down things like inadvertent copy constructor/assignment operator calls, automatic memory allocs, and heavy-weight operator overloads, all of which are an inexhaustible source of untraceable performance bugs. In other words, C++ as a language is right at the sweet spot where it does not guarantee safety, while at the same time making performance unpredictable.
- mrkline 10y ago> inadvertent copy constructor/assignment operator calls This is much less of a problem (and much more controllable!) now that we have move semantics. > automatic memory allocs It's hard to accidentally allocate memory if you don't have a system allocator hooked up. > heavy-weight operator overloads No more heavy-weight than a standard function call, and usually inlined at that.
- omtose 10y agoI never understood why people argue that operator overload is a bad thing. In a language that doesn't support it, you're going to have a function "T add(T, T)" which is pretty much the same, and can do anything. Overloading "T operator+(T, T)" is mostly syntactic sugar.
- leovonl 10y agoFirst hand 5-year experience with embedded and C++ here. I used to work with a big C++ codebase which implemented ISDN/R2/SIP stacks (and a few more protocols), running inside an embedded ARM. Now I mostly work with a C codebase that does similar things. I can say with good confidence that most of what was written on the article about compiler flags, etc, can be regarded as premature optimization - ie, you just need to start from this point if you know your environment is really constrained and exceptions are too much of a cost - which is usually not the case in modern embedded ARM systems. About the advantages, I completely agree with the safety issue. Reuse is also much easier - using generic programming concepts to better encapsulate your abstractions, including functions acting on different types (templates), you can rely on sizeof and/or properties of the types themselves to specialize the proper behaviour. All without having a single virtual/dynamic dispatch. And modern C++ is making this much easier to use. TBH I never used a single virtual in any of my code, though we used to have that in a few places in the whole stack away from the performance-sensitive code paths. Comparing to C, there's a lot of repeated patterns in the code I work nowadays, and it's a bit frustrating as I can't really abstract them sometimes, and there's some repetition of similar algorithms in different places. You can start doing callbacks, some ugly acrobatics with macros, and some other alternatives, but the code then becomes unreadable, a minefield, or both.
- mrkline 10y ago> you just need to start from this point if you know your environment is really constrained and exceptions are too much of a cost - which is usually not the case in modern embedded ARM systems. ARM systems really run the gamut these days - while many are quite powerful (see: my phone), many also fall on the more traditional microcontroller side, with very little in terms of flash and RAM. In case it wasn't clear, this article focused on the latter.
- pjmlp 10y agoAn ARM Cortex-M4 is already powerful enough to run a Java runtime. http://www.microej.com/products/device-software-development/microej-os/ http://www.microej.com/products/device-software-development/...
- Animats 10y agoThe Ardunio environment is C++; the Arduino people just don't emphasize that. Much of the stuff that needs heap allocation isn't there, but all the compile time class machinery is.
- ChuckMcM 10y agocrosstools-NG is a PITA, the ARM team maintains a solid toolchain for the Cortex series at http://launchpad.net/gcc-arm-embedded/ http://launchpad.net/gcc-arm-embedded/ you can even load it by PPA on Debian/Ubuntu systems. For the larger parts there is also a perfectly functional memory allocator in newlib. So you can "go wild" if you want, although as the author points out, newlib is not without its race conditions for multi-threaded code.
- mrkline 10y agoThe main issue with just using newlib's allocator is that we're using FreeRTOS, and (AFAIK), there isn't a good way to make the two aware of each other. One could also probably hook operator new up to to FreeRTOS, but we try to avoid dynamic memory allocation after init, like the article said.
- rkangel 10y ago> (AFAIK), there isn't a good way to make the two aware of each other When you set up FreeRTOS you configure which heap implementation it uses. They provide a number of heapX.c files you can choose between. heap3.c uses malloc directly for instance, the others use built-in implementations of a heap algorithm of varying complexity. If you want to use your own allocator, you just write your own heapX.c file. Use the malloc one as a template and call the newlib allocator instead of malloc. Link that in instead of any other heapX file and voila, FreeRTOS is using newlib to allocate memory.
- mrkline 10y agoIIRC, the concern was in the details of newlib's allocator. Its sbrk looks for a linker symbol, then starts slicing memory off of that address. There were worries that unless we were careful, it might stomp on FreeRTOS. (These worries could have been unfounded, but we didn't look into it deeply. We only dynamically allocate at startup, so we'd prefer FreeRTOS's heap_1.c anyways.)
- 10y ago
- lultimouomo 10y ago> operator delete is required whenever we give a base class a virtual destructor—as is standard practice—even if we never heap-allocate an object of that class. I'm not sure why you would need a virtual destructor if you don't heap allocate a class and are not going to call delete, as it will not be polymorfically deleted anyway, so you can do with a non-virtual destructor.
- mrkline 10y agoThe main motivation is just that experienced C++ devs (myself included) have the rule, "base classes should have virtual destructors" drummed into their heads. Defining operator delete (even if the compiler elides it since, like you pointed out, it's never needed) allows devs to continue that habit without any negative consequences.
- minipci1321 10y agoThis makes instances of all derived classes be at least as long as a pointer -- many of them will be adding a data member so be longer yet, which will disqualify them for passing over in a general-purpose register (details per each ABI). This can have dramatic adverse effect on the overall performance of the code which, depending on the domain, can be very negative. EDIT: actually, adding a virtual, or a destructor, alone (without size considerations) makes the type non-POD which prevents it from being returned in a register.
- pandaman 10y agoTo be honest, a derived class already cannot be a POD. But stuffing the vtable pointer into any derived class is indeed wasteful for embedded programming and opens another way to exploit your system (if you care about security) by leaving code pointers at the fixed addresses in r/w memory.
- gpderetta 10y agoit can still be standard layout (the 'new' POD for all intents and purposes) if either the base or the derived class is empty. /pedantic
- eliangidoni 10y agoI would not use C++ on firmware though. Usually memory/space requirements are far more important than OOP lang features. And good software can be developed without them.
- bobmoretti 10y agoC++, especially modern standards of the language, offer far more than OOP features. /If/ you know the language and tools well, there is no reason that C++ won't be as efficient in space and time as the equivalent C code. C++ offers real gains to be had over C for embedded software, with rich (if a bit cryptic) zero-overhead abstractions, and higher level constructs that can eliminate entire classes of errors.
- wott 10y agoNothing guarantees that it is zero-overhead, it all depends on the efforts, quality and mood of the C++ compiler. Whereas in C you can at least rely on the fact that even without any complex optimisation it will at worst produce machine code that looks 99% like the C code, because it maps 1 -> 0.99. Good luck telling what is the complexity hidden behind a C++ operator.
- eliangidoni 10y agoRight, that was my point. You have to use time/effort on understanding the compiler workings, time that could be used to focus on your actual problem and features implementation. For firmware I wouldn't.
- atroyn 10y agoWhat is a good resource for getting started with this kind of development? I've done some write-an-OS tutorials but nothing with bare-metal or RTOS yet, and I'd like to.