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

新手上路,请多包涵

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

原文由 eonil 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 845
1 个回答

大多数编译器都使用预定义的宏,您可以在 此处 找到列表。 GCC 编译器预定义的宏可以在 这里 找到。这是 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, tvOS, or watchOS Simulator
    #elif TARGET_OS_MACCATALYST
         // Mac's Catalyst (ports iOS API into Mac, like UIKit).
    #elif TARGET_OS_IPHONE
        // iOS, tvOS, or watchOS device
    #elif TARGET_OS_MAC
        // Other kinds of Apple platforms
    #else
    #   error "Unknown Apple platform"
    #endif
#elif __ANDROID__
    // Below __linux__ check should be enough to handle Android,
    // but something may be unique to Android.
#elif __linux__
    // linux
#elif __unix__ // all unices not caught above
    // Unix
#elif defined(_POSIX_VERSION)
    // POSIX
#else
#   error "Unknown compiler"
#endif

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

The _WIN64 #ifdef can be nested into the _WIN32 #ifdef because _WIN32 is even defined when targeting the Windows x64版本。如果某些标头包含对两者都是通用的,这可以防止代码重复(还有 WIN32 没有下划线允许 IDE 突出显示正确的代码分区)。

原文由 Evgeny Gavrin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题