Conditional compilation in C++ based on operating system

M. Dudley picture M. Dudley · May 24, 2009 · Viewed 9k times · Source

I would like to write a cross-platform function in C++ that contains system calls. What conditional compilation flags can I check to determine which operating system the code is being compiled for? I'm interested mostly in Windows and Linux, using Visual Studio and GCC.

I think it should look something like this:

void SomeClass::SomeFunction()
{
    // Other code

#ifdef LINUX
    LinuxSystemCall();
#endif

#ifdef WINDOWS
    WindowsSystemCall();
#endif

    // Other code
}

Answer

Thilo-Alexander Ginkel picture Thilo-Alexander Ginkel · May 25, 2009

My gcc (4.3.3) defines the following Linux-related predefined macros:

$ gcc -dM -E - < /dev/null | grep -i linux
#define __linux 1
#define __linux__ 1
#define __gnu_linux__ 1
#define linux 1

Under VC++ (and many other Win32 compilers) there are also a couple of predefined macros identifying the platform, most notably _WIN32. Further details: http://msdn.microsoft.com/en-us/library/b0084kay(VS.80).aspx