我试图更新我的c++编译器到c++ 11。 我已经搜索了一点,我得出的结论是,我必须使用标志-std=c++0x或-std=gnu++0x,但我不知道很多关于标志的事情。有人能帮帮我吗?(我使用的是Ubuntu 12.04。)

以下是我试图使用c++ 11中包含的库(即数组)时从编译器得到的错误:

#include <array>
#include <iostream>

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

该文件需要即将发布的ISO c++标准c++ 0x的编译器和库支持。这种支持目前是实验性的,必须使用-std=c++0x或-std=gnu++0x编译器选项来启用。


你的Ubuntu肯定有最新版本的g++。要使用的标志是-std=c++0x。

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

假设你从命令行(终端)调用g++:

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

or

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

如果以上都不奏效。

如果你想保留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.

你可以通过命令检查你的g++:

which g++
g++ --version

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

要切换到g++ 4.7(假设你已经在你的机器上安装了它),运行:

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来检查切换是否正确。

现在用

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

你可以参考下面的链接来了解哪个版本的编译器支持哪些功能。它拥有现代编译器中功能支持的详尽列表。GCC似乎非常严格地遵循标准,并且先于任何其他编译器实现。

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

g++ source_file.cpp -o executable_name -std=c++11 for c++11 g++ source_file.cpp -o executable_name -std=c++14 for c++14 g++ source_file.cpp -o executable_name -std=c++17 for c++17 g++ source_file.cpp -o executable_name -std=c++2a for c++ 20,目前还不支持c++ 20的所有特性。请参考此链接以获得GCC中的特性支持列表。

这个列表变化得很快,如果你在等待某个特定的特性得到支持,请密切关注这个列表。

对于ISO c++11使用-std=c++11编译器标志。 有关c++编译器标志和选项的更多详细信息,请检查这个。