How to compile a C++ 11 code by gcc?

c++
gcc
Category Software and digital electronics / Coding
2022-12-26 23:55

My code

I have written the following C++11 code:

main.cpp
#include <iostream>

using std::cout;
using std::endl;

int main()
{
    for(int x : {2,3,5,7,11,13})
    {
        cout << x << endl;        
    }
    return 0;
}

Compilation error

When I compile my code using gcc I face with an error:

g++ main.cpp

The error message is

error: deducing from brace-enclosed initializer list requires '#include <initializer_list>'

How should I fix it?

Answered by robin
2022-12-31 04:31

Solution

You need to enable c++11 settings:

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

This helps your code compiles with no error.

Problem background

In the recent versions of gcc, it follows c++11 standard by default.

You might be using an old version of gcc.

Try

g++ --version

to know your gcc version.

×

Login

No account?
Terms of use
Forgot password?