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

问题描述 投票:83回答:5

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

#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

还是一样。

c++ multithreading g++ c++11
5个回答
98
投票

我认为在Linux上,pthread用于实现std::thread,因此您需要指定-pthread编译器选项。

由于这是一个链接选项,因此该编译器选项需要在源文件之后:

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

6
投票

除了使用-std=c++0x-pthread,你不能使用-static


4
投票

-std=c++11 -static -pthread -Wl,--whole-archive -lpthread -Wl,--no-whole-archive-static一起工作!

见这里:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52590#c4


3
投票

这是一个简单的CMake文件,用于编译使用线程的C ++ 11程序:

的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

1
投票

尝试在单个命令中以这种方式编译:

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

您也可以尝试使用C ++ 11而不是gnu ++ 11。希望这有效。

© www.soinside.com 2019 - 2024. All rights reserved.