C++ 在 linux 下的 GCC 中使用 std::thread 的正确链接选项是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8649828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are the correct link options to use std::thread in GCC under linux?
提问by Earth Engine
Hi I am trying to use std::thread
with G++. Here is my test code
嗨,我正在尝试std::thread
与 G++一起使用。这是我的测试代码
#include <thread>
#include <iostream>
int main(int, char **){
std::thread tt([](){ std::cout<<"Thread!"<<std::endl; });
tt.join();
}
It compiles, but when I try to run it the result is:
它可以编译,但是当我尝试运行它时,结果是:
terminate called after throwing an instance of 'std::system_error'
what(): Operation not permitted
Aborted
My compiler version:
我的编译器版本:
$ 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.
What is wrong with my test code?
我的测试代码有什么问题?
UPDATE: I use the following command line to compile and run my code.
更新:我使用以下命令行来编译和运行我的代码。
$ g++ -std=c++0x test.cpp
$ ./a.out
and I tried
我试过
$ g++ -std=c++0x -lpthread test.cpp
$ ./a.out
still the same.
还是一样。
回答by hmjd
I think on Linux pthread is used to implement std::thread
so you need to specify the -pthread
compiler option.
我认为在Linux上使用pthread来实现std::thread
所以需要指定-pthread
编译器选项。
As this is a linking option, this compiler option need to be AFTERthe source files:
由于这是一个连接选项,这个编译器选项需要被后的源文件:
$ g++ -std=c++0x test.cpp -pthread
回答by Bowie Owens
In addition to using -std=c++0x
and -pthread
you must notuse -static
.
除了使用-std=c++0x
,-pthread
你一定不要使用-static
.
回答by tuvalu
-std=c++11 -static -pthread -Wl,--whole-archive -lpthread -Wl,--no-whole-archive
works together with -static
!!!
-std=c++11 -static -pthread -Wl,--whole-archive -lpthread -Wl,--no-whole-archive
一起工作-static
!!!
See here: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52590#c4
回答by Alexander
Here's a simple CMake file for compiling a C++11 program that uses threads:
这是一个简单的 CMake 文件,用于编译使用线程的 C++11 程序:
CMakeLists.txt:
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
回答by Ravi Shankar
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.
你也可以试试 C++11 而不是 gnu++11。希望这有效。