我正在尝试在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上这样做。
在CLion中,要使用标志-pthread进行编译,您应该将以下行添加到CMakeLists.txt(我已经测试并且它可以工作):
SET(CMAKE_CXX_FLAGS -pthread)
确保在CMakeLists.txt的末尾链接到pthread
target_link_libraries(${PROJECT_NAME} pthread)
你必须使用标志-lpthread
或-pthread
(通常建议使用pthread
)进行编译。如果您正在使用CLion,那么您将需要编辑CMakeLists.txt以确保使用此标志编译代码,方法是使用以下命令设置编译器标志:
SET( CMAKE_CXX_FLAGS "<other compiler flags> -pthread")
您可以在this post上了解有关这些选项的更多信息。