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

您好,我正在尝试使用与 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

还是老样子。

63511 次浏览

I think on Linux pthread is used to implement std::thread so you need to specify the -pthread compiler option.

As this is a linking option, this compiler option need to be AFTER the source files:

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

Here's a simple CMake file for compiling a C++11 program that uses threads:

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)

One way of building it is:

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

In addition to using -std=c++0x and -pthread you must not use -static.

-std=c++11 -static -pthread -Wl,--whole-archive -lpthread -Wl,--no-whole-archive works together with -static!!!

See here: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52590#c4

Try compiling this way in single command:

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

You can also try C++11 instead of gnu++11. Hope this works.