Using c++ in microcontrollers
Please tell me, is it possible to use C++ for programming microcontrollers?
Are there any restrictions for the C++language?
4 answers
You can use it often, but you need to look at the specific implementation. For example, there may be no exceptions.
On the other hand, c++ brings a certain overhead, and on microcontrollers, every byte is often important, this is not java with large servers, where you can buy a bar or two.
But microcontrollers do not stand still and develop, as do compilers. Perhaps for your controller and your case, C++ is the best option.
C++ can and should be used for programming microcontrollers. As it was written here, no exceptions and new operators. To cancel exceptions, there is even a compiler flag, especially for us. Why C++ is better than C:
- Strict typing. If something is wrong, get an error when compiling, rather than looking for it in debugging. A good example, if an enumeration type is passed to a function, and you entered something wrong in C (int, for example), then you will be compiled in C, in C++ get a compilation error.
- Links. The C++ philosophy: "don't pay for what you don't need." Links do not take up space in memory, and code with links looks neater than code with pointers. You can always forget to put * or&.
- Classes (structures). It is banal to describe not only the structure itself, but also the actions with it. Each register can be wrapped in a class wrapper with methods that indicate by their name what you are doing. If the code needs a lot of comments, then this is bad code.
- Objects. In the function (class, class method) , you can pass a reference to the output object of the microcontroller, and not write a bunch of defines of all registers (it is easy to make a mistake, fix a lot, especially for all stm32).
- Templates. Forget about multi-line macros, errors in which it is extremely difficult to debug, the debugger will simply not enter them. Templates are much better than a preprocessor.
- There is no overhead. This is a common myth. Competent code written in c++ gives less volume binaries, I came across research, even videos from conferences are on YouTube. (I think it's all the fault of links instead of pointers and template optimization).
In fact, there are no restrictions, you just need a proper linker script with the appropriate sections to support exceptions and virtual methods, as well as the release of allocators/deallocators and STL (of course this is a luxury?). It is not difficult to find a script on the network...
Look at the Wiring language used in Arduino. This is C++ without the standard library and exceptions, with its own special library. It is compiled, by the way, mentioned in your avr-gcc tags.