Following up on this comment from the question Writing firmware: assembly or high level?:
When compiling C++ code for the Arduino platform, can you use virtual functions, exceptions, etc? Or would you want to (have to) use a subset of C++ (as described in the comment)?
Any other caveats when programming for the Arduino platform?
You get the same runtime performance as a C++ member function call, but without any compile-time checking to enforce access control. In C, virtual function calls look unlike any other kind of function call.
Hence, Virtual functions cannot be static in C++.
Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call. Functions are declared with a virtual keyword in base class. The resolving of function call is done at runtime.
The Arduino environment uses the AVR version of the GCC toolchain. The code is compiled as C++, so you can use classes. Virtual functions are possible; the vtables will be stored in the .data section and have the correct addresses. In fact, the Print base class uses virtual functions to adapt the various "print" methods to the different output types.
Exceptions are not supported because of code space reasons. The Arduino environment passes "-fno-exceptions" to the compiler command line. See the source for verification of this.
Templates are supported. For example, this no-cost stream insertion operator technique works fine using a simple template and inline operator.
The Arduino software uses avr-gcc to compile sketches. The following limitations were sourced from the avrlibc FAQ (Can I use C++ on the AVR?):
Supported
Not supported
new
and delete
(attempting to use them will cause the linker to complain about undefined external references). This means that objects can only be created on the stack. If dynamic memory allocation is required it must be implemented using malloc()
and free()
of C
types-fno-exceptions
in the compiler options. This is done automatically by the Arduino IDE when it launches avr-gcc
Other issues
extern "C" { . . . }
The usability of a features is not limited by the platform but rather the compiler that you are using.
I would check your compiler documentation on what language features are supported.
Comeau computing has a C++ to C compiler which supports all C++ features. Not just virtual functions, or exceptions, but also export. You would need to call Comeau to get it to target the Arduino language, but should be not too hard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With