Search code examples
c++conditional-compilation

C++ conditional compilation with large numbers of code files


I wanna compile and run one copy of C++ codes on Windows and Linux. so I need to use conditional compilation(CC). However, it comes across the problem that how to use CC in large numbers of code files.

Such as, I have:

//A.cpp
#define _WINDOWS_
#ifdef _WINDOWS_
#include <windows.h>
//some code for windows
#else
#include <pthread.h>
//some code for linux
#endif

and I also have B.cpp, C.cpp...

Should I write "#define _WINDOWS_" in every single file, or is there a better way?

And I have tried to do like this:

  1. create a head file Platform.h

     #ifndef _PLAT_
     #define _PLAT_
     #define _WINDOWS_
     #endif
    
  2. include the file Platform.h, like:

     //A.cpp
     #include "Platform.h"
     #ifdef _WINDOWS_
     #include <windows.h>
     //some code for windows
     #else
     #include <pthread.h>
     //some code for linux
     #endif
    
  3. it compiles with errors! Maybe including "Platform.h" before including <windows.h> causes the errors.


Solution

  • Use some predefined macro from your compiler.

    http://sourceforge.net/p/predef/wiki/OperatingSystems/

    #ifdef _WIN32
    // Code specific to Windows.
    #elif defined __linux__ // Many variants; check the link above.
    // Code specific to Linux.
    #else
    // Portable code.
    #endif
    

    This will work in the majority of the cases.

    Note that most of these macros are used to detect the host operating system (that is, the system in which you're building the program), not the target operating system (the system in which the resulting program is intended to be run). However, it is usually the case that both systems coincide. Note also that whether any of these macros are actually predefined obviously depends on your particular compiler.

    If all else fails (for example, target system differs from host, or your compiler is strange enough to not predefine any system-detection macros at all), simply define any of them in the compiler's command line (for example, using -D in POSIX-compliant C compilers) by putting it into your build script or makefile. Don't write such #defines in the header themselves.