makefile不适用于-std = c ++ 11选项

coo*_*aac 1 c++ gcc makefile c++11

我正在尝试使用g ++ 4.8.2和以下makefile来使用一些C++ 11特性

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)    
Run Code Online (Sandbox Code Playgroud)

但是当我打电话给"make"时,这是我得到的错误信息

$ 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
Run Code Online (Sandbox Code Playgroud)

在我看来,-std = c ++ 11没有被拾取,所以我试图在一堆不同的地方抛出该选项,但仍然发生相同的错误.

目前的解决方法是直接使用命令行,这对我有用

$ 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
Run Code Online (Sandbox Code Playgroud)

我只是想知道为什么makefile不会做同样的事情,以及如何更新makefile以使用-std = c ++ 11选项.

jua*_*nza 7

你的makefile存在各种问题,但主要的问题似乎是你用.cpp文件创建对象的规则是错误的.你需要一些东西

%.o : %.cpp
    $(CC)  $(CFLAGS) $< -o $@
Run Code Online (Sandbox Code Playgroud)

在另一方面,它可能是更容易利用make潜规则,并设置CXXFLAGS,CXX等等.例如,设定

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

并删除%.o规则,让make做它的事情.需要注意的是CCCFLAGS通常用于C代码.