3 ms·
The real reason to use C over C++ is that when you can't use heap allocated memory, you can't use 90+% of C++. At that point, you've inflicted upon yourself al
by bsder 4y ago
The real reason to use C over C++ is that when you can't use heap allocated memory, you can't use 90+% of C++. At that point, you've inflicted upon yourself all the C++ footguns and have thrown away any of the C++ useful bits.
Once that happens, you might as well just use C.
- pclmulqdq 4y agoI disagree with you here. Off the top of my head, these are the things I like about embedded C++ (and embedded Rust): * 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.
- mananaysiempre 4y agoHaving just written a truly repulsive preprocessor hack, I’m currently in my “maybe C++’s monster of a semantics is not that bad actually” phase (it is that bad though, so that’ll pass). C’s metaprogramming facilities are severely lacking. And yet— > Until C gets 'defer', the cleanest alternative is gotos. In an embedded setting, a given project is probably only ever targeting a single compiler, and given that in non-exotic situations it’s a vendor fork of GCC, you should be fine using GCC-specific features. And __attribute__((cleanup)) (essentially a block-scoped defer with cleanup code exiled to a separate function) has been in GCC since (checks docs) version 3.3, from 2003. It would have to be a truly spectacular vendor GCC fork to be missing that feature. (For reference, the year 2003 also saw the release of Linux kernel 2.6, as in two-six-zero.)
- elteto 4y agoYou can’t use 90% of the STL, sure. But there’s nothing in C++ that requires heap allocation (maybe exceptions? But those are turned off in embedded code anyways)