It seems to me people consistently shy away from, or rather vehemently oppose the use of, C++ on microcontrollers, but I can\'t for the life of me figure out why. If you sta
is there really any noticeable difference between C vs C++?
In my experience there is a big difference in the usage of RAM.
For example: I am currently working on C++ for an ARM uC with 512KB FALSH and 64KB of RAM. RAM usage should be less than 30kB but is twice that because every const ends up in RAM. That is because it is nearly impossible (at least with GCC and ARM targets) to convince the compiler to leave const class members in FLASH. The only way to achive this is by using constructor-less classes, declaring all const members public and using aggregate initializer lists.
To make things worse, C++ does not allow members to be named in the initializer list like you can do in plain C:
struct St { int b; int a[3]; }; static const struct St st_array[2] = { [1] = { .a = {1,2,3,}, .b = 10, }, // deliberately disordered to [0] = { .b = 8, .a = { 4,5,6,}, }, // illustate the value of names. };
All C-compilers will put these constants into the "constant data" segment (in FLASH).
In C++ you would have to do this:
class ClassA // cannot have constructor or destructor { public: // const data cannot be private for aggregate initialization const int b; const int a[3]; private: int priv_fn(int i); public: int pub_fn(); }; static ClassA classA_array[2] = { { 3, { 8, 9,10,}, }, // aggregate initialization { 4, { 9,10,11,}, }, // better get the order right!!! };
Depending on your compiler, even this may not guarantee that the constants stay in FLASH.
And yes I know, with C++0x you can use initializer lists with the constructor and that is what I am doing, but the moment you have a constructor which gets called at runtime, all initializations become dynamic.
The technical report (thanks MSalters) confirms this:
7.1.2 Constructors and ROMable Objects In general, const objects of classes with constructors must be dynamically initialized. However, in some cases compile-time initialization could be performed if static analysis ...
The bottom line is that such static analysis is not done by any compiler I have available and if I have to limit myself to constructor-less classes with public consts and without initializer naming then I might as well write in plain (and object-oriented) C.