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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4605842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:54:34  来源:igfitidea点击:

How to identify platform/compiler from preprocessor macros?

c++macroscross-platformc-preprocessor

提问by Arenim

I'm writing a cross-platform code, which should compile at linux, windows, Mac OS. On windows, I must support visual studio and mingw.

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

There are some pieces of platform-specific code, which I should place in #ifdef .. #endifenvironment. For example, here I placed win32 specific code:

有一些特定于平台的代码,我应该将它们放在#ifdef .. #endif环境中。比如我这里放了win32的具体代码:

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

But how do I recognize linux and mac OS? What are defines names (or etc.) I should use?

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

回答by karlphillip

For Mac OS:

对于Mac 操作系统

#ifdef __APPLE__

For MingWon Windows:

对于Windows 上的MingW

#ifdef __MINGW32__

For Linux:

对于Linux

#ifdef __linux__

For other Windows compilers, check this threadand thisfor several other compilers and architectures.

对于其他Windows编译器,检查此线程这个其他几个编译器和架构。

回答by John Bartholomew

See: http://predef.sourceforge.net/index.php

见:http: //predef.sourceforge.net/index.php

This project provides a reasonably comprehensive listing of pre-defined #definesfor many operating systems, compilers, language and platform standards, and standard libraries.

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

回答by rubenvb

Here's what I use:

这是我使用的:

#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

EDIT:Although the above might work for the basics, remember to verify what macro you want to check for by looking at the Boost.Predef reference pages. Or just use Boost.Predef directly.

编辑:虽然上述内容可能适用于基础知识,但请记住通过查看Boost.Predef 参考页面来验证您要检查的宏。或者直接使用Boost.Predef。

回答by rvalue

If you're writing C++, I can't recommend using the Boostlibraries strongly enough.

如果您正在编写 C++,我不建议您足够强烈地使用Boost库。

The latest version (1.55) includes a new Predeflibrary which covers exactly what you're looking for, along with dozens of other platform and architecture recognition macros.

最新版本 (1.55) 包括一个新的Predef库,它完全涵盖了您正在寻找的内容,以及许多其他平台和架构识别宏。

#include <boost/predef.h>

// ...

#if BOOST_OS_WINDOWS

#elif BOOST_OS_LINUX

#elif BOOST_OS_MACOS

#endif