perimosocordiae perimosocordiae - 2 months ago 8
C Question

How do I check OS with a preprocessor directive?

I need my code to do different things based on the operating system on which it gets compiled. I'm looking for something like this:

#ifdef OSisWindows
//define something for Windows
#else
//define it for a Unix machine
#endif


Is there a way to do this? Is there a better way to do the same thing?

Answer

There are predefined macros that are used by most compilers, you can find the list here

Otherwise, you will have to adjust the build system so a macro like OS_WINDOWS/OS_UNIX gets defined during compilation, then you will have to check it in the code using ifdef.

#ifdef OS_WINDOWS
   //define something for Windows
#else
  //define it for a Unix machine
#endif
Comments