C++ 如何在编译时测试当前版本的 GCC?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/259248/
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-27 14:06:41  来源:igfitidea点击:

How to test the current version of GCC at compile time?

c++cgccversions

提问by PierreBdR

I would like to include a different file depending on the version of GCC. More precisely I want to write:

我想根据 GCC 的版本包含不同的文件。更准确地说,我想写:

#if GCC_VERSION >= 4.2
#  include <unordered_map>
#  define EXT std
#elif GCC_VERSION >= 4
#  include <tr1/unordered_map>
#  define EXT std
#else
#  include <ext/hash_map>
#  define unordered_map __gnu_cxx::hash_map
#  define EXT __gnu_cxx
#endif

I don't care about gcc before 3.2.

我不在乎 3.2 之前的 gcc。

I am pretty sure there is a variable defined at preprocessing time for that, I just can't find it again.

我很确定在预处理时定义了一个变量,我只是找不到它。

采纳答案by PierreBdR

Ok, after more searches, it one possible way of doing it is using __GNUC_PREREQdefined in features.h.

好的,经过更多的搜索,一种可能的方法是使用__GNUC_PREREQ定义在features.h.

#ifdef __GNUC__
#  include <features.h>
#  if __GNUC_PREREQ(4,0)
//      If  gcc_version >= 4.0
#  elif __GNUC_PREREQ(3,2)
//       If gcc_version >= 3.2
#  else
//       Else
#  endif
#else
//    If not gcc
#endif

回答by luke

There are a number of macros that should be defined for your needs:

应根据您的需要定义许多宏:

__GNUC__              // major
__GNUC_MINOR__        // minor
__GNUC_PATCHLEVEL__   // patch

The version format is major.minor.patch, e.g. 4.0.2

版本格式为major.minor.patch,例如4.0.2

The documentation for these can be found here.

可以在此处找到这些文档。

回答by Martin York

As a side note:

作为旁注:

To find all the predefined macros:

要查找所有预定义的宏:

  • Create empty file t.cpp
  • g++ -E -dM t.cpp
  • 创建空文件 t.cpp
  • g++ -E -dM t.cpp