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

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

最佳答案

大多数编译器都使用预定义的宏,您可以找到列表here . GCC 编译器预定义的宏可以找到 here . 以下是 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

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

_WIN64 #ifdef 可以嵌套到 _WIN32 #ifdef 因为 _WIN32 甚至在针对 Windows x64 版本时定义。如果某些 header 包含对两者都是通用的,这可以防止代码重复 (也 WIN32 不带下划线允许 IDE 突出显示正确的代码分区。

https://stackoverflow.com/questions/5919996/

相关文章:

c++ - C++单元测试框架比较

c++ - 如何检查元素是否在 std::set 中?

c++ - 用 C 或 C++ 为 Android 编写应用程序?

c++ - 类成员函数模板可以是虚拟的吗?

c++ - 将二维数组传递给 C++ 函数

c++ - C/C++ 中字符的大小 ('a' )

c++ - 为什么 C++ 编译器不定义 operator== 和 operator!=?

c++ - 以理智、安全和有效的方式复制文件

c++ - 如何循环遍历 map 的 C++ map ?

c++ - 结合 C++ 和 C - #ifdef __cplusplus 如何工作?