首页 > 解决方案 > 将 g++ 模式设置为 C++11

问题描述

我正在尝试构建需要 C++11 的 cmake 源代码。构建停止,显然抱怨是未检测到 C++11。g++模式实际上设置为-std=gnu++17

这是控制台日志的一部分

---------------------------------------------
CMake 3.18.20200919, Copyright 2000-2020 Kitware, Inc. and Contributors
Found GNU toolchain
C compiler on this system is: gcc   
C++ compiler on this system is: g++  -std=gnu++17  
Makefile processor on this system is: make
g++ has setenv
g++ has unsetenv
g++ does not have environ in stdlib.h
g++ has stl wstring
g++ has <ext/stdio_filebuf.h>
---------------------------------------------
g++  -std=gnu++17      -DCMAKE_BOOTSTRAP    -DCMake_HAVE_CXX_MAKE_UNIQUE=1  -c $HOME/Apps/CMake-master/Source/cmAddCustomCommandCommand.cxx -o cmAddCustomCommandCommand.o

这是日志文件中错误的一部分...

In file included from /usr/include/c++/5/unordered_map:35:0,
                 from cmake_bootstrap_11920_test.cxx:4:
/usr/include/c++/5/bits/c++0x_warning.h:32:2: error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support must be enabled with the -std=c++11 or -std=gnu++11 compiler options.
 #error This file requires compiler and library support \
  ^
cmake_bootstrap_11920_test.cxx:7:2: error: #error "Compiler is not in a mode aware of C++11."
 #error "Compiler is not in a mode aware of C++11."
  ^
cmake_bootstrap_11920_test.cxx:70:16: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
   int Member = 1;

在网上四处寻找,我注意到 C++11 仅在 gcc 版本 4.6 之后可用。我检查了我的版本,它似乎在上面。

g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609

我知道 -std=c++11 标志用于启用 g++ 中的 C++11 功能,但我似乎不知道在这种情况下我在做什么。我尝试编辑 CompileFlags.cmake 文件,但没有发生任何变化。

我来到这个指向我正在使用的 cmake 源的页面。它说...

bootstrap: Require compiler mode aware of C++11

Some compilers have enough features enabled in their default modes to
pass our simple C++11 unique_ptr check but do not enable enough to build
CMake.  Poison this case so that we choose one of the explicit `-std=`
options for such compilers.

不确定这到底是什么意思。

我究竟如何将 g++ 模式更改为 C++11,以便在运行引导命令时使用 C++11?或者,换句话说,如何将 std 更改为指向 C++11 (-std=c++11)?

标签: c++11cmakeg++

解决方案


首先,您的主机 PC 中安装了 g++ 版本 5.4.0,这很好,因为这意味着它也支持您想要使用的 C++11。要设置它,您可以在CMakeList.txt文件中定义它:

set (CMAKE_CXX_STANDARD 11)

这应该够了吧。另请检查文档:

https://cmake.org/cmake/help/v3.1/variable/CMAKE_CXX_STANDARD.html

通常,我建议使用编译器支持的最新标准(https://gcc.gnu.org/projects/cxx-status.html),因为您还将获得该标准中引入的最新功能。如果您使用的是遗留代码,则例外。


推荐阅读