如何在 makefile 中包含 -std=c++11 和 -lpthread?

How to include -std=c++11 and -lpthread in makefile?

我尝试了 this answer 中的建议,但它是针对 GCC 的,无论如何都没有帮助。

我想 #include <thread> 在一个文件中,所以我有一个 make 文件如下:

OBJS    = clitest.o Sources/NClient.o
CC      = g++
DEBUG   = -g
CFLAGS  = -Wall -c $(DEBUG)
LFLAGS  = -Wall $(DEBUG)

clitest: $(OBJS)
    $(CC) $(LFLAGS) $(OBJS) -o clitest

我应该在哪里包含 -std=c++11-lpthread? 我已经尝试了几乎所有可能的组合,但是当我 运行 make:

时我继续收到此错误

/usr/include/c++/4.8.3/bits/c++0x_warning.h:32:2: error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options.

我相信这是 运行ning 的命令?

[jaska@localhost NClient]make
g++    -c -o clitest.o clitest.cpp

这里还有源代码文件:

#include <thread>
#include <string>

void task(std::string msg){
    std::cout << msg << '\n';
}

...
...

std::thread t1(task, "message");
client->create();
t1.join();

添加到 CFLAGSLFLAGS

CFLAGS  = -Wall -c $(DEBUG) -std=c++11 -pthread
LFLAGS  = -Wall $(DEBUG) -std=c++11 -pthread

应该够了。

对于隐式规则也会覆盖 CXXFLAGS 变量

CXXFLAGS  = -Wall -c $(DEBUG) -std=c++11 -pthread

正如您从命令行输出中看到的那样

[jaska@localhost NClient]make
g++    -c -o clitest.o clitest.cpp

CFLAGS 中的其他标志也未用于编译。

它们是 gcc/g++ 或链接器 ld 的有效命令行参数。因此,它们必须作为 CFLAGS 和 LFLAGS 的附加项传递(或者可能作为 CXXFLAGS、CPPFLAGS、LDFLAGS,具体取决于 Makefile 的功能)。你的例子并没有显示你将 CFLAGS 传递给 C++ 编译器,所以这也是有问题的。显式传递它或为您的 C++ 编译器设置 CXXFLAGS(C 不是 C++)。

我建议您首先在命令行上解决您的问题,然后在问题解决后转到 Makefile。实际上,您正在尝试让 Make 创建行:

g++ -Wall -g -std=c++11 -pthread clitest.o Sources/NCLient.o -o clitest

您的 makefile 没有明确的规则来编译 $(OBJS) 中的对象,因此这意味着将使用隐式规则,这就是产生此命令的原因:

g++    -c -o clitest.o clitest.cpp

.cpp 文件转换为 .o 文件的隐含规则约为:

$(CXX) $(CXXFLAGS) -c -o $@ $<

所以要添加影响该规则的选项,您应该将它们添加到 CXXFLAGS 变量(CFLAGS 通常用于编译 C 文件,而 CC 是 C 编译器, C++ 编译器的常规变量是 CXX).

-lpthread 选项是一个 linker 选项,因此需要在 linking 期间给出。您已经为 linking 定义了自己的规则,因此您应该将 -lpthread 添加到该配方或将其添加到 LFLAGS 变量。

N.B。在 linking 期间使用 -Wall-g 是无用的,它们没有任何效果。

N.B。将 -c 添加到 CFLAGS 是错误的,编译 .c 文件的隐式规则已经包含 -c,就像 C++ 文件的隐式规则包含 -c 一样。这不会导致任何问题,因为 CFLAGS 变量未被您的 makefile 或编译 .cpp 文件的隐式规则使用。

N.B。而不是 linking 到 -lpthread 你应该用 -pthread

编译 and link

N.B。 linking 的隐含规则和 makefile 约定是对 linker 选项使用变量 LDFLAGS,对 -lpthread 等库使用 LIBS,所以我会将您的 makefile 重写为:

OBJS    = clitest.o Sources/NClient.o
CXX     = g++
DEBUG   = -g
CXXFLAGS  = -Wall $(DEBUG) -std=c++11 -pthread
LDFLAGS = -pthread

clitest: $(OBJS)
    $(CXX) $(LDFLAGS) -o $@ $^ $(LIBS)

这仍然依赖于将 .cpp 文件转换为 .o 文件的隐式规则,但现在该隐式规则将从 CXXFLAGS 变量中选取正确的选项。