Eon*_*nil 291 c c++ cross-platform c-preprocessor os-detection
如果有一些跨平台的C/C++代码应该在Mac OS X,iOS,Linux,Windows上编译,我如何在预处理器进程中可靠地检测它们?
Evg*_*rin 479
大多数编译器都使用预定义的宏,您可以在此处找到列表.可以在此处找到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 Simulator
#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
Run Code Online (Sandbox Code Playgroud)
定义的宏取决于您将要使用的编译器.
该_WIN64
#ifdef
可嵌套到_WIN32
#ifdef
,因为_WIN32
针对Windows,不仅在x86版本时被定义.如果某些包含对两者都是通用的,则可以防止代码重复.
Pat*_*Fog 29
正如Jake所指出的,TARGET_IPHONE_SIMULATOR是TARGET_OS_IPHONE的子集.
此外,TARGET_OS_IPHONE是TARGET_OS_MAC的子集.
所以更好的方法可能是:
#ifdef _WIN64
//define something for Windows (64-bit)
#elif _WIN32
//define something for Windows (32-bit)
#elif __APPLE__
#include "TargetConditionals.h"
#if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR
// define something for simulator
#elif TARGET_OS_IPHONE
// define something for iphone
#else
#define TARGET_OS_OSX 1
// define something for OSX
#endif
#elif __linux
// linux
#elif __unix // all unices not caught above
// Unix
#elif __posix
// POSIX
#endif
Run Code Online (Sandbox Code Playgroud)
一个必然的答案:[此站点]上的人花了一些时间为每个OS /编译器对定义宏表。
例如,您可以看到 _WIN32
在Windows上未使用Cygwin(POSIX)定义它,而在Windows,Cygwin(非POSIX)和MinGW上使用每个可用的编译器(Clang,GNU,Intel等)进行编译时都未定义。 。
无论如何,我发现这些表非常有用,并认为我会在这里分享。
归档时间: |
|
查看次数: |
141528 次 |
最近记录: |