Compiling C++11 with g++

I'm trying to update my C++ compiler to C++11. I have searched a bit and I have come to the conclusion that I have to use the flag -std=c++0x or -std=gnu++0x, but I don't know many things about flags. Can anyone help me? (I'm using Ubuntu 12.04.)

Here is the error that I get from the compiler when I attempt to use a library which is included in C++11 (i.e. array):

#include <array>
#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.


Flags (or compiler options) are nothing but ordinary command line arguments passed to the compiler executable.

Assuming you are invoking g++ from the command line (terminal):

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

or

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

if the above doesn't work.


You can check your g++ by command:

which g++
g++ --version

this will tell you which complier is currently it is pointing.

To switch to g++ 4.7 (assuming that you have installed it in your machine),run:

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

Then select 2 as selection(My machine already pointing to g++ 4.7,so the *)

Once you switch the complier then again run g++ --version to check the switching has happened correctly.

Now compile your program with

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

You can refer to following link to know which features are supported in which version of compiler. It has an exhaustive list of feature support in modern compilers. Seems like GCC follows the standard very closely and implements before any other compiler.

Regarding your question, you can compile using

  1. g++ source_file.cpp -o executable_name -std=c++11 for C++11
  2. g++ source_file.cpp -o executable_name -std=c++14 for C++14
  3. g++ source_file.cpp -o executable_name -std=c++17 for C++17
  4. g++ source_file.cpp -o executable_name -std=c++2a for C++20, All the features of C++20 are not yet supported. Refer to this link for feature support list in GCC.

The list changes pretty fast, keep an eye on the list, if you are waiting for a particular feature to be supported.