关于c ++:用g ++编译C ++ 11

Compiling C++11 with g++

我尝试更新我的C++编译器到C++ 11。我查了一下,得出的结论是,我必须使用国旗-std=c++0x-std=gnu++0x,但我对国旗不太了解。有人能帮我吗?(我使用的是Ubuntu 12.04。)

这里是当我尝试使用包含在C++ 11(即数组)中的库时,从编译器得到的错误:

1
2
3
4
5
6
7
8
#include
#include <iostream>

int main()
{
    std::array<int, 3> arr = {2, 3, 5};
    ...
}

This file requires compiler and library support for the upcoming ISO C++ standard, C++0x. This support is currently experimental, and must be enabled with the -std=c++0x or -std=gnu++0x compiler options.


标志(或编译器选项)只是传递给编译器可执行文件的普通命令行参数。

假设您正在从命令行(终端)调用g+:

$ g++ -std=c++11 your_file.cpp -o your_program

$ g++ -std=c++0x your_file.cpp -o your_program

如果上述方法无效。


您可以通过命令检查您的g++

1
2
which g++
g++ --version

这将告诉您当前它指向的是哪个编译器。

要切换到g++4.7(假设您已将其安装到计算机中),请运行:

1
2
3
4
5
6
7
8
9
sudo update-alternatives --config gcc

There are 2 choices for the alternative gcc (providing /usr/bin/gcc).

  Selection    Path              Priority   Status
------------------------------------------------------------
  0            /usr/bin/gcc-4.6   60        auto mode
  1            /usr/bin/gcc-4.6   60        manual mode
* 2            /usr/bin/gcc-4.7   40        manual mode

然后选择2作为选择(我的机器已经指向g++4.7,所以*)

切换编译器后,再次运行g++ --version,检查切换是否正确。

现在用编译程序

1
g++ -std=c++11 your_file.cpp -o main


你的Ubuntu肯定有一个足够新版本的G++。要使用的标志是-std=c++0x


如果要保留GNU编译器扩展,请使用-STD= GNU+0X,而不是-STD= C++0X。

The compiler can accept several base standards, such as c89 or c++98,
and GNU dialects of those standards, such as gnu89 or gnu++98. By
specifying a base standard, the compiler will accept all programs
following that standard and those using GNU extensions that do not
contradict it. For example, -std=c89 turns off certain features of GCC
that are incompatible with ISO C90, such as the"asm" and"typeof"
keywords, but not other GNU extensions that do not have a meaning in
ISO C90, such as omitting the middle term of a"?:" expression. On the
other hand, by specifying a GNU dialect of a standard, all features
the compiler support are enabled, even when those features change the
meaning of the base standard and some strict-conforming programs may
be rejected. The particular standard is used by -pedantic to identify
which features are GNU extensions given that version of the standard.
For example-std=gnu89 -pedantic would warn about C++ style //
comments, while -std=gnu99 -pedantic would not.


您可以参考以下链接,特定版本的编译器支持哪些功能。它有一个完整的编译器功能支持列表。看起来gcc严格遵循标准并在任何其他编译器之前实现。

关于您的问题,您可以使用

  • 对C++ 11的EDCOX1〔8〕
  • 对C++ 14的EDCOX1〔9〕
  • 对C++ 17的EDCOX1〔10〕
  • 对于C++ 20,EDCOX1为11,尽管尚未支持C++ 20的所有特性,但请参阅GCC中的特征支持列表的链接。
  • 如果您正在等待特定的功能得到支持,那么列表的变化非常快,请密切关注列表。