A. *_*pez 6 c++ pthreads c++11 clion
我正在尝试在CLion中运行这个简单的线程c ++程序
#include <iostream>
#include <thread>
using namespace std;
//Start of the thread t1
void hello() {
cout << "Hello,concurrent world!" << endl; }
int main() {
thread t1(hello); // spawn new thread that calls hello()
cout << "Concurrency has started!" << endl;
t1.join();
cout << "Concurrency completed!";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是有一个未定义的引用pthread的错误,我没有看出我做错了什么...请注意我在CLion上这样做.
小智 13
在CLion中,要使用标志-pthread进行编译,您应该将以下行添加到CMakeLists.txt(我已经测试并且它可以工作):
SET(CMAKE_CXX_FLAGS -pthread)
Run Code Online (Sandbox Code Playgroud)
首先CMake找到包:
find_package(Threads REQUIRED)
Run Code Online (Sandbox Code Playgroud)
然后链接到它:
target_link_libraries(${PROJECT_NAME} Threads::Threads)
Run Code Online (Sandbox Code Playgroud)
现在构建将成功完成链接步骤。
您必须使用标志-lpthread或进行编译-pthread(通常建议使用pthread)。如果您使用 CLion,那么您将需要编辑 CMakeLists.txt,以确保通过使用以下命令设置编译器标志来使用此标志编译您的代码:
SET( CMAKE_CXX_FLAGS "<other compiler flags> -pthread")
Run Code Online (Sandbox Code Playgroud)
您可以在这篇文章中了解有关这些选项的更多信息。