Search code examples
ccompilationcross-compilingbare-metal

Compiler check to ensure I'm running in bare-metal and not in a hosted environment


If I'm compiling a C program for bare-metal, I know I can insert things like

#if defined(__linux__) 
#error "You're not using a cross-compiler."
#endif`

But, I don't want to check for every operating system. Is there a single check to see if I'm in a hosted environment?


Solution

  • If you want to determine that you are building with -ffreestanding then make your code check for the __STDC_HOSTED__ macro. It will be set to 1 for normal code and set to 0 for a freestanding build.

    See the GCC info pages or the docs. The relevant quote is

    By default, it acts as the compiler for a hosted implementation, defining 'STDC_HOSTED' as '1' and presuming that when the names of ISO C functions are used, they have the semantics defined in the standard. To make it act as a conforming freestanding implementation for a freestanding environment, use the option '-ffreestanding'; it then defines 'STDC_HOSTED' to '0' and does not make assumptions about the meanings of function names from the standard library, with exceptions noted below.