C++ compiling on Windows and Linux: ifdef switch

Sardathrion - against SE abuse picture Sardathrion - against SE abuse · Jul 11, 2011 · Viewed 190.8k times · Source

I want to run some c++ code on Linux and Windows. There are some pieces of code that I want to include only for one operating system and not the other. Is there a standard #ifdef that once can use?

Something like:

  #ifdef LINUX_KEY_WORD
    ... // linux code goes here.
  #elif WINDOWS_KEY_WORD
    ... // windows code goes here.
  #else 
  #error "OS not supported!"
  #endif

The question is indeed a duplicate but the answers here are much better, especially the accepted one.

Answer

Muhammad Anjum Kaiser picture Muhammad Anjum Kaiser · Jul 11, 2011

use:

#ifdef __linux__ 
    //linux code goes here
#elif _WIN32
    // windows code goes here
#else

#endif