0

C++ has many aspects, included by default, that are not desirable or even functional on embedded bare metal / free standing platforms.

How can I configure g++ to compile C++ in a manner suitable for embedded bare-metal / freestanding?

SRobertJames
  • 8,210
  • 14
  • 60
  • 107
  • Related: [How do you create a freestanding C++ program?](https://stackoverflow.com/q/2089619/2402272) – John Bollinger Mar 13 '22 at 14:50
  • Supposing a general-purpose `g++` that does not build for a freestanding environment by default, if the `-ffreestanding` option does not work then I don't know what would. – John Bollinger Mar 13 '22 at 14:51
  • are you talking about compiling or linking the compiling is the easy part and should not be much of a problem. now the linking, esp for C++, esp for bare metal, can be difficult. – old_timer Mar 14 '22 at 02:06

1 Answers1

1

The compiler option -ffreestanding is explicitly there for this purpose. It enables implementation-defined forms of main and it will disable various assumptions about standard library functions, optimizing code a bit differently in some situations.

Unfortunately in terms of of main(), C++ explicitly doesn't allow void main (void) as an implementation-defined form, unlike C. There is no sensible solution to this, it's a language flaw. Name it main_ or some such.

However, this doesn't disable or block any dangerous and unsuitable C++ features from being used - that burden lies on the programmer who picked C++. You have to manually ensure that things like heap allocation, RTTI, exceptions and so on aren't present. Removing the entire heap segment from your linker script is a sensible thing to do - it should block things like std::vector or std::string from linking.

Then depending on target, there might be certain suitable gcc compiler ports. Such as in case of ARM where one compiler port is called "gcc-none-eabi", which would be the suitable one for bare metal Cortex M microcontrollers.

At a minimum, you'll need a "C run-time" (CRT) for the target - either use one provided by the tool chain (generally recommended) or create one yourself (compile with -nostdlib). It's not a beginner task to create one, particularly not for targets with advanced MMUs. Some general advise of how to do so here. Creating one for C++ is slightly more intricate than for C, since it also has to include all constructor calls to static storage duration objects.

Lundin
  • 195,001
  • 40
  • 254
  • 396