c++cpreprocessorconditional-compilationpredefined-macro

How does the compiler predefine the OS-specific preprocessors like __linux__, __apple__, etc.?


It's common to use the predefined preprocessors __linux__ and __apple__ for conditional compilation like this:

#if defined(__linux__)
inline void foo() {
    // Linux-specific implementation
}
#endif

#if defined(__apple__)
inline void foo() {
    // macOS-specific implementation
}
#endif

int main() {}

However, if I compile it with clang main.cpp, especially in case of cross-compilation, how does the compiler know which preprocessor should be predefined? __linux__ or __apple__ ?


Solution

  • Normally the compiler knows the platform it is compiling to, and the target architecture is clear to the compiler, it will automatically feed those macros defined to the preprocessor, as if them had been included as -D parameters on the command line or an special definitions file had been inserted at the beginning of the source (as if means exactly that, you don't specify those parameters in the command line, but the compiler behaves as if those parameters had been specified at the start of the file)

    You normally have an option to allow the compiler to show the whole set of automatic macro definitions it adds to the compilation unit before preprocessing.