简体   繁体   English

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

[英]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 我正在尝试使用带有以下makefile的g ++ 4.8.2来玩一些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)    

But when I call "make", here's the error message I get 但是当我调用“ 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

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. 在我看来,-std = c ++ 11没有被使用,因此我试图在多个不同的地方抛出该选项,但是仍然发生相同的错误。

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

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. 生成文件存在各种问题,但主要的问题似乎是您根据.cpp文件创建对象的规则是错误的。 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 另一方面,利用make隐式规则并设置CXXFLAGSCXX等可能会更容易。例如,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. 并删除%.o规则,让它去做。 Note that CC and CFLAGS are typically used for C code. 请注意, CCCFLAGS通常用于C代码。

I think the space in your .cpp .o: rule is confusing make. 我认为您的.cpp .o:规则中的空格令人困惑。 But I'd go with @juanchopanza's recommendation and switch to the newer pattern syntax - it is much more clear. 但是我会接受@juanchopanza的建议,并切换到较新的模式语法-这更加清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM