如果有一些跨平台的 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 突出显示正确的代码分区。
关于c++ - 如何在 C 预处理器中可靠地检测 Mac OS X、iOS、Linux、Windows?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5919996/