166 points · by dlcmh · 3y ago · 25 comments
The real reason to use C in embedded programming is that "vendor_forked_gcc_from_10_years_ago" is your only compiler on most platforms, and almost certainly does not support C++ or has some bugs in its C++ compiler implementation.
There’s only a handful of things that matter when it comes to generating embedded code for a specific microcontroller and most of it comes down to the format required for the final linked executable, which usually boils down to an ld script.
In general any kind of ARM chip is going to work perfectly fine with the latest C++.
Or to rephrase your comment, the real reason to use C is because all the support tooling, header files, peripheral drivers, RTOS, etc. are written in C, and there’s not a huge benefit to moving user code to C++.
For rare targets, there's just no money in making a compiler work for more than this small subset of C. My favorite example is the compiler for a really strange architecture where everything is 24 bits. Char is short is long is a pointer.
Bigger controllers tend to be ARM-based, so it's getting better.
Also Tricore has a big share, but their compiler support is getting better. There was even a rust compiler being announced recently, though I doubt it's using LLVM backend, so it's likely to be behind in terms of features.
I remember using a vendor fork of GCC 2 (released in 1999) to compile for a specific microcontroller in 2015, but since that vendor now releases Cortex-M0's, the vendor-blessed compiler uses a near-mainline GCC.
Once that happens, you might as well just use C.
* RAII makes modern C++ a lot cleaner for things like holding locks, disabling interrupts, and other stuff that needs to be unwound at function exit, and doesn't need heap allocation. Until C gets 'defer', the cleanest alternative is gotos.
* Operator overloading is pretty nice for code where you have custom data types (like 2-element vectors), which can be very common with DSP systems.
* References give you a non-nullable pointer type.
* Template-based data structures are much nicer than the C alternative: macros.
* std::array is kind of nice, and doesn't have dynamic memory. Also, while std::string is pretty unsafe, std::string_view is very nice!
* For the few dynamic data structures you may want to use, you can write a quick allocator and hook that into every std data structure you want rather than writing your own data structures. The "null allocator" strategy is an option: just return the same pointer to one fixed chunk of memory, and fail if the data structure grows too big. You can also do the "init allocator" strategy: Only allow dynamic allocation during initialization.