如何从预处理器宏中识别平台/编译器?

时间:2011-01-05 15:31:16

标签: c++ macros cross-platform c-preprocessor

我正在编写一个跨平台的代码,它应该在linux,windows,Mac OS上编译。在Windows上,我必须支持visual studio和mingw。

有一些特定于平台的代码,我应该放在#ifdef .. #endif环境中。例如,这里我放置了win32特定代码:

#ifdef WIN32
#include <windows.h>
#endif

但是如何识别linux和mac OS?我应该使用什么定义名称(或等)?

4 个答案:

答案 0 :(得分:128)

Mac OS

#ifdef __APPLE__

对于Windows上的 MingW

#ifdef __MINGW32__

Linux

#ifdef __linux__

对于其他Windows编译器,请检查this threadthis以了解其他几个编译器和体系结构。

答案 1 :(得分:59)

请参阅:http://predef.sourceforge.net/index.php

该项目为许多操作系统,编译器,语言和平台标准以及标准库提供了相当全面的预定义#defines列表。

答案 2 :(得分:43)

以下是我使用的内容:

#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。

答案 3 :(得分:19)

如果您正在编写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