問題描述
如果有一些跨平臺的 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
因為_WIN32
code> 甚至在面向 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).
這篇關于如何在 C 預處理器中可靠地檢測 Mac OS X、iOS、Linux、Windows?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!