如何知道gcc/g++ 的默认C++版本

C++在C++ 11之后在保持向后兼容的情况下,语法增强了非常多,变化很大。得益于Move语义,和一些标准库的改进(如std::list的size()函数在C++11之前是O(n)的复杂度,从C++11开始变成常数复杂度)。一些旧C++代码即使什么改动也不做,只需要在新的C++标准下编译,也能获得性能提升。一般要给g++开启C++11需要用 -std=c++11,开启C++17则是 -std=c++17。那么,如果不添加这些选项,gcc/g++默认使用的C++版本号是什么呢?

如果你的gcc/g++版本号大于4.7的话,可以用如下命令获得默认c++版本。

kamus@shyyp.net:~g++ --version | head -1
g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
kamus@shyyp.net:~ g++ -dM -E -x c++  /dev/null | grep -F __cplusplus
#define __cplusplus 201402L
kamus@shyyp.net:~$ gcc -dM -E -x c++  /dev/null | grep -F __cplusplus    #其实用gcc也可以
#define __cplusplus 201402L

如上所示,我的g++版本是9.3.0。它的默认C++版本是C++14。
这是我家用的电脑。我在公司的机器上运行结果如下:

kamuszhou@centos ~ g++ --version | head -1
g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
kamuszhou@centos~ g++ -dM -E -x c++  /dev/null | grep -F __cplusplus
#define __cplusplus 199711L

如上所示,老版的g++ 4.8.4用的默认C++版本还是c++98

再解释一下这里用到的gcc/g++的选项, 这里-dM的意思是:

Instead of the normal output, generate a list of ‘#define’ directives for all the macros defined during the execution of the preprocessor, including predefined macros. This gives you a way of finding out what is predefined in your version of the preprocessor.

对所有宏,包括预定义的宏,在预编译阶段输出一系列的#define。

-E的意思是,做完预编译后即退出,不执行真正的编译。
-x c++表示使用C++语言。

Leave a Reply

Your email address will not be published. Required fields are marked *