对pthread CLion的未定义引用

问题描述 投票:3回答:3

我正在尝试在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;
   }

我的问题是有一个未定义的引用pthread的错误,我没有看出我做错了什么...请注意我在CLion上这样做。

c++ c++11 pthreads clion
3个回答
9
投票

在CLion中,要使用标志-pthread进行编译,您应该将以下行添加到CMakeLists.txt(我已经测试并且它可以工作):

SET(CMAKE_CXX_FLAGS -pthread)

0
投票

确保在CMakeLists.txt的末尾链接到pthread

target_link_libraries(${PROJECT_NAME} pthread)

0
投票

你必须使用标志-lpthread-pthread(通常建议使用pthread)进行编译。如果您正在使用CLion,那么您将需要编辑CMakeLists.txt以确保使用此标志编译代码,方法是使用以下命令设置编译器标志:

SET( CMAKE_CXX_FLAGS  "<other compiler flags> -pthread")

您可以在this post上了解有关这些选项的更多信息。

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