0

I installed qt 4.7.4 and gcc 4.6.1. I tried to compile this program but it won't compile for me:
Why cannot I compile this code?

#include <QApplication>
#include <iostream>
using std::cout;

int main(int argc, char** argv)
{
    QApplication app(argc,argv);
    int a[] = {1,2};
    for (auto e : a)
    {
        cout << e << '\n';
    }
    return app.exec();
}  

Error:
C:...\main.cpp:9: error: 'e' does not name a type

smallB
  • 16,662
  • 33
  • 107
  • 151
  • 7
    I think I speak for everyone when I say we're sorry to hear that. What is your question? Care to tell us what the error was? – Widor Nov 02 '11 at 12:48
  • @Widor the question (implicitly) is why cannot I compile it, but I'll update it. – smallB Nov 02 '11 at 12:50
  • 1
    What command are you using to compile it? (your using c++11, and so you will need to tell g++ this via compiler flags: try `g++ file.cpp --std=c++0x`) – Tom Nov 02 '11 at 12:53
  • Most probably your compiler does not understand this new c++ feature. – hochl Nov 02 '11 at 12:56
  • @Tom where (via QTCreator) am I suppose to put those options – smallB Nov 02 '11 at 13:02

5 Answers5

4

for (auto e : a)
is a range based for loop from the c++11 standard. You need to enable the c++11 in gcc with the -std=c++0x command line.

mkaes
  • 13,781
  • 10
  • 52
  • 72
  • where (via QTCreator) am I suppose to put those options ? – smallB Nov 02 '11 at 13:03
  • I never used QtCreator. But this link should answer the question. http://stackoverflow.com/questions/2987062/configuring-the-gcc-compiler-switches-in-qt-qtcreator-and-qmake – mkaes Nov 02 '11 at 13:14
  • yes, this seems to solve the problem, great pity you cannot set it via some dialog. Thanks. – smallB Nov 02 '11 at 13:16
2

For me this works (g++ 4.6.1, Qt 4.7.1):

g++ --std=c++0x -I$QTDIR/include/QtGui -I$QTDIR/include \
    test.cpp -L$QTDIR/lib -lQtCore -lQtGui
hochl
  • 12,524
  • 10
  • 53
  • 87
1

You need --std=c++0x compiler flag.

anio
  • 8,903
  • 7
  • 35
  • 53
0

My guess is that qtcreator (and qmake) does not feed the compiler with the flag instructing it to use C++2011.

Didier Trosset
  • 36,376
  • 13
  • 83
  • 122
0

First, you want to be sure that your C++ file is compiled with the C++11 dialect (ie using -std=c++0x flag to g++) since you use the auto type inference feature.

Then, I think that your for loop might not be valid. Perhaps you want a to be a std::vector<int>

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547