如何在C预处理器中可靠地检测Mac OS X,iOS,Linux,Windows?

时间:2011-05-07 08:37:51

标签: c++ c cross-platform c-preprocessor os-detection

如果有一些应该在Mac OS X,iOS,Linux,Windows上编译的跨平台C / C ++代码,如何在预处理器过程中可靠地检测它们?

3 个答案:

答案 0 :(得分:464)

大多数编译器都使用预定义的宏,您可以找到列表here。可以找到GCC编译器预定义的宏here。 这是gcc的一个例子:

#ifdef _WIN32
   //define something for Windows (32-bit and 64-bit, this part is common)
   #ifdef _WIN64
      //define something for Windows (64-bit only)
   #else
      //define something for Windows (32-bit only)
   #endif
#elif __APPLE__
    #include "TargetConditionals.h"
    #if TARGET_IPHONE_SIMULATOR
         // iOS Simulator
    #elif TARGET_OS_IPHONE
        // iOS device
    #elif TARGET_OS_MAC
        // Other kinds of Mac OS
    #else
    #   error "Unknown Apple platform"
    #endif
#elif __linux__
    // linux
#elif __unix__ // all unices not caught above
    // Unix
#elif defined(_POSIX_VERSION)
    // POSIX
#else
#   error "Unknown compiler"
#endif

定义的宏取决于您将要使用的编译器。

_WIN64 #ifdef可以嵌套到_WIN32 #ifdef中,因为在定位Windows时定义了_WIN32,而不仅仅是x86版本。如果某些包含对两者都是通用的,则可以防止代码重复。

答案 1 :(得分:29)

正如Jake所指出的,TARGET_IPHONE_SIMULATOR是TARGET_OS_IPHONE的子集。

此外,TARGET_OS_IPHONE是TARGET_OS_MAC的子集。

所以更好的方法可能是:

#ifdef _WIN64
   //define something for Windows (64-bit)
#elif _WIN32
   //define something for Windows (32-bit)
#elif __APPLE__
    #include "TargetConditionals.h"
    #if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR
        // define something for simulator   
    #elif TARGET_OS_IPHONE
        // define something for iphone  
    #else
        #define TARGET_OS_OSX 1
        // define something for OSX
    #endif
#elif __linux
    // linux
#elif __unix // all unices not caught above
    // Unix
#elif __posix
    // POSIX
#endif

答案 2 :(得分:5)

一种推论答案:[this site]上的人们花时间为每个OS /编译器对定义宏表。

例如,您可以看到_WIN32未在Windows上使用Cygwin(POSIX)定义,而它是在Windows,Cygwin(非POSIX)和MinGW上使用每个可用编译器定义的(Clang) ,GNU,英特尔等)。

无论如何,我发现这些表格非常丰富,并且认为我在这里分享。