寫跨平臺c/c++程序的時候,需要搞清各平臺下面的預編譯宏,區分各平臺代碼。而跨平臺c/c++編程,GCC基本在各平臺都可以使用。整理了一份各平臺預編譯宏的判斷示例。
需要注意幾點:
* windows32/64平臺_WIN32都會被定義,而_WIN64只在64位windows上定義,因此要先判斷_WIN64
* 所有的apple系統都會定義 __APPLE__,包括MacOSX和iOS
* TARGET_IPHONE_SIMULATOR 是 TARGET_OS_IPHONE 的子集,
TARGET_OS_IPHONE 是 TARGET_OS_MAC的子集。也就是說iOS模擬器上會同時定義這三個宏。因此判斷的時候要先判斷子集。
* 另外mac上可以用以下命令行獲取GCC定義的預編譯宏:
gcc -arch i386 -dM -E - < /dev/null | sort (i386可替換爲arm64等)
參考示例:
(來自 https://stackoverflow.com/questions/5919996/how-to-detect-reliably-mac-os-x-ios)
#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 __ANDROID__
// android
#elif __linux__
// linux
#elif __unix__ // all unices not caught above
// Unix
#elif defined(_POSIX_VERSION)
// POSIX
#else
# error "Unknown compiler"
#endif