编译器检查以确保我 运行 在裸机环境中而不是在托管环境中

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

如果我正在为裸机编译 C 程序,我知道我可以插入

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

但是,我不想检查每个操作系统。是否有单一检查来查看我是否处于托管环境中?

如果您想确定您正在使用 -ffreestanding 进行构建,请检查您的代码是否存在 __STDC_HOSTED__ 宏。对于普通代码,它将设置为 1,对于独立构建,它将设置为 0。

查看 GCC 信息页面或文档。相关报价是

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.