cookieisaac cookieisaac - 3 months ago 9
C++ Question

makefile doesn't work with -std=c++11 option

I'm trying to play with some C++11 features using g++ 4.8.2 with the following makefile

CC=g++
DEBUG=-g
CFLAGS=-c -Wall -std=c++11 $(DEBUG)
LFLAGS = -Wall -std=c++11 $(DEBUG)
SOURCES=test.cpp
OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=test

all: $(SOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
$(CC) $(LFLAGS) $(OBJECTS) -o $@ -std=c++11
.cpp .o:
$(CC) $(CFLAGS) $< -o $@ -std=c++11

clean:
rm -rf *o $(EXECUTABLE)


But when I call "make", here's the error message I get

$ make
g++ -c -o test.o test.cpp
test.cpp: In function ‘int main()’:
test.cpp:18:15: error: range-based ‘for’ loops are not allowed in C++98 mode
for (int i : {2, 3, 5, 7, 9, 13, 17, 19})
^
make: *** [test.o] Error 1


It seems to me that -std=c++11 isn't picked up, so I have tried to throw that option in bunch of different places, but still same error occurs.

Current workaround is to use command line directly, and that works for me

$ cat test.cpp
#include <iostream>

using namespace std;

int main()
{
cout << "Hello World" << endl;

for (int i : {2, 3, 5, 7, 9, 13, 17, 19})
{
cout << i << " ";
}
cout << endl;
return 0;
}

$ g++ -std=c++11 test.cpp -o test -W
$ ./test
Hello World
2 3 5 7 9 13 17 19


I am just wondering why makefile doesn't do the same thing, and how I could update the makefile to use -std=c++11 option.

Answer

There are various issues with your makefile, but the main one seems to be that your rule for creating objects out of .cpp files is wrong. You need something along the lines of

%.o : %.cpp
    $(CC)  $(CFLAGS) $< -o $@

On the other hand, it might be easier to leverage make's implicit rules, and set CXXFLAGS, CXX etc. For example, set

CXX = g++
CXXFLAGS = -Wall -std=c++11 $(DEBUG)
CPPFLAGS += .... # pre-processor flags, for include paths etc.

and remove the %.o rule, letting make do its thing. Note that CC and CFLAGS are typically used for C code.