首页 文章

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

提问于
浏览
271

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

3 回答

  • 29

    大多数编译器都使用预定义的宏,您可以找到列表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 中,因为 _WIN32 是在定位Windows时定义的,而不仅仅是x86版本 . 如果某些包含对两者都是通用的,则可以防止代码重复 .

  • 444

    正如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
    
  • 4

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

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

    无论如何,我发现这些表格非常丰富,我想我会在这里分享 .

相关问题