在Linux下使用GCC,使用std::thread的正确链接选项是什么?

92

嗨,我正在尝试在 G++ 中使用 std::thread。这是我的测试代码:

#include <thread>
#include <iostream>

int main(int, char **){
    std::thread tt([](){ std::cout<<"Thread!"<<std::endl; });
    tt.join();
}

它可以编译,但当我尝试运行时结果是:

terminate called after throwing an instance of 'std::system_error'
  what():  Operation not permitted 
Aborted

我的编译器版本:

$ g++ --version
g++ (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

我的测试代码有什么问题?

更新:我使用以下命令行来编译和运行我的代码。

$ g++ -std=c++0x test.cpp
$ ./a.out

我尝试过

$ g++ -std=c++0x -lpthread test.cpp
$ ./a.out

仍然是一样的。


7
@Earth Engine:这个stackoverflow回答解释了为什么没有pthread库也不会出现链接错误:https://dev59.com/T2025IYBdhLWcg3wAhDp#6266345 简而言之, glibc 为许多pthread函数提供了无操作存根。 - Michael Burr
@EarthEngine,您能否将解决方案放在回答中?特别是要求-lpthread必须跟随源文件。 - River
5个回答

107

我认为在Linux系统中,使用pthread来实现std::thread,因此需要指定-pthread编译器选项。

由于这是一个链接选项,所以这个编译器选项需要放在源文件之后:

$ g++ -std=c++0x test.cpp -pthread

我正在尝试使用gcc 4.7.1编译一个非常简单的程序,但是我遇到了"操作不允许"的错误。问题在于我已经使用了-pthread标志。你知道还有其他的标志吗? - Filipe Felisbino
6
我将移除链接器选项中的"-static"标志,这样就解决了问题。不知道为什么会出现这种情况。 - Filipe Felisbino
我想知道为什么编译时没有使用 -lpthread 选项却没有报错,有人知道吗? - zeus2
我先尝试了编译器选项-pthread,但这并没有解决问题。当我加上-lpthread时,它就可以工作了(但我没有单独尝试过-lpthread)。 - gbmhunter
1
在Ubuntu 14.04下,g++ --version的输出为(g++ (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1)。我需要添加-Wl, --no-as-needed参数,然后运行g++ --std=c++11 -Wl, --no-as-needed -pthread main.cc。 - Begui
1
-Wl,-整个归档 -lpthread -Wl,-无整个归档 解决问题,而不是-pthread。这是链接问题链接。根据 man gcc-pthread 只是 g++ 选项,它添加了多线程支持,设置了预处理器和链接器的标志。 - Denis Zaikin

6
除了使用-std=c++0x-pthread之外,您不应该使用-static

5

使用 --whole-archive 会使得文件变得非常庞大。我发现 另一个答案 中的静态链接方法在 OpenWRT 上适用于我。 - mlt

2
以下是一个用于编译使用线程的C++11程序的简单CMake文件:
CMakeLists.txt:
cmake_minimum_required(VERSION 2.8)
list(APPEND CMAKE_CXX_FLAGS "-pthread -std=c++11 ${CMAKE_CXX_FLAGS}")
add_executable(main main.cpp)

一种构建它的方法是:

mkdir -p build
cd build
cmake .. && make

2
你的解决方案对于我来说并没有比hmjd的答案更好,反而添加了不必要的东西(分析、测试覆盖率)。 - Max Beikirch

1

尝试以单个命令的方式编译:

g++ your_prog.cpp -o your_output_binary -lpthread -std=gnu++11

你可以尝试使用C++11而不是gnu++11。希望这能起作用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接