How do I check OS with a preprocessor directive?

前端 未结 16 1601
星月不相逢
星月不相逢 2020-11-22 13:53

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
// do         


        
16条回答
  •  半阙折子戏
    2020-11-22 14:30

    There is no standard macro that is set according to C standard. Some C compilers will set one on some platforms (e.g. Apple's patched GCC sets a macro to indicate that it is compiling on an Apple system and for the Darwin platform). Your platform and/or your C compiler might set something as well, but there is no general way.

    Like hayalci said, it's best to have these macros set in your build process somehow. It is easy to define a macro with most compilers without modifying the code. You can simply pass -D MACRO to GCC, i.e.

    gcc -D Windows
    gcc -D UNIX
    

    And in your code:

    #if defined(Windows)
    // do some cool Windows stuff
    #elif defined(UNIX)
    // do some cool Unix stuff
    #else
    #    error Unsupported operating system
    #endif
    

提交回复
热议问题