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

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

If there's some cross-platform C/C++ code that should be compiled on Mac OS X, iOS, Linux, Windows, how can I detect them reliably during preprocessor process?

推荐答案

有大多数编译器使用的预定义宏,你可以找到列表 此处.GCC 编译器预定义宏可以在此处找到.以下是 gcc 的示例:

There are predefined macros that are used by most compilers, you can find the list here. GCC compiler predefined macros can be found here. Here is an example for gcc:

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
   //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
    #if TARGET_OS_MACCATALYST
         // Mac's Catalyst (ports iOS API into Mac, like UIKit).
    #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

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

The defined macros depend on the compiler that you are going to use.

_WIN64 #ifdef 可以嵌套到_WIN32 #ifdef 因为_WIN32code> 甚至在面向 Windows x64 版本时定义.如果某些标头包含对两者通用,则这可以防止代码重复(也WIN32 没有下划线允许IDE 突出显示代码的正确分区).

The _WIN64 #ifdef can be nested into the _WIN32 #ifdef because _WIN32 is even defined when targeting the Windows x64 version. This prevents code duplication if some header includes are common to both (also WIN32 without underscore allows IDE to highlight the right partition of code).

相关文章