我正在编写一个跨平台代码,它应该在 linux、windows、Mac OS 上编译。在windows上,我必须支持visual studio和mingw。
有一些特定于平台的代码,我应该将它们放在 #ifdef .. #endif
环境中。比如这里我放了win32的具体代码:
#ifdef WIN32
#include <windows.h>
#endif
但是我如何识别 linux 和 mac OS 呢?我应该使用什么定义名称(或等)?
对于 Mac 操作系统:
#ifdef __APPLE__
对于 Windows 上的 MingW:
#ifdef __MINGW32__
对于 Linux:
#ifdef __linux__
对于其他 Windows 编译器,请检查 this thread 和 this 以了解其他几个编译器和体系结构。
请参阅:http://predef.sourceforge.net/index.php
该项目为许多操作系统、编译器、语言和平台标准以及标准库提供了相当全面的预定义 #defines
列表。
这是我使用的:
#ifdef _WIN32 // note the underscore: without it, it's not msdn official!
// Windows (x64 and x86)
#elif __unix__ // all unices, not all compilers
// Unix
#elif __linux__
// linux
#elif __APPLE__
// Mac OS, not sure if this is covered by __posix__ and/or __unix__ though...
#endif
编辑:虽然上述内容可能适用于基础知识,但请记住通过查看 Boost.Predef reference pages 来验证您要检查的宏。或者直接使用 Boost.Predef。
#if
询问是否已定义,其他则测试价值。如果做 #elif defined(__unix__)
等会更一致,我认为。
如果您正在编写 C++,我不建议您足够强烈地使用 Boost 库。
最新版本 (1.55) 包括一个新的 Predef 库,其中涵盖了 exactly what you're looking for,以及许多其他平台和体系结构识别宏。
#include <boost/predef.h>
// ...
#if BOOST_OS_WINDOWS
#elif BOOST_OS_LINUX
#elif BOOST_OS_MACOS
#endif
不定期副业成功案例分享
__APPLE__
是否区分 OSX 和 iOS?__APPLE__
为 OS X 和 iOS 设置。您可以在#ifdef __APPLE__
中使用#include <TargetConditionals.h>
,然后它会为您提供TARGET_OS_IPHONE #define
。__MINGW64__
在使用 mingw64 时也可用__MINGW64__
,因此认为 Windows/MSVC 的_MSC_VER
值得一提(也可用于检查 MSVC 版本)。