Arduino C++ code: can you use virtual functions and exceptions?


Question

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?

1
15
5/23/2017 12:32:11 PM

Accepted Answer

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.

14
4/10/2012 7:33:00 PM

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

  • Virtual functions
  • Constructors and destructors (including global ones)

Not supported

  • C++ standard functions, classes, and template classes (but see this port of uClibc++ for Arduino)
  • operators 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
  • Exceptions. Since exceptions are enabled by default in the C++ frontend, they explicitly need to be turned off using -fno-exceptions in the compiler options. This is done automatically by the Arduino IDE when it launches avr-gcc

Other issues

  • Some of the supplied include files are not C++ safe, i.e. they need to be wrapped with
    extern "C" { . . . }

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon