【问题标题】:Undefined reference to pthread CLion对 pthread CLion 的未定义引用
【发布时间】:2017-08-09 22:50:09
【问题描述】:

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


【解决方案1】:

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

SET(CMAKE_CXX_FLAGS -pthread)

【讨论】:

  • 它对我有用,但我还必须添加 find_package(Threads)
  • @PaulLaffitte 它对我有用,无需添加 find_package(Threads)
  • 我投反对票不是因为这是一个糟糕的答案,在撰写本文时还可以。但是,最佳实践是现在使用 find_package(…) 并链接到 Threads::Threads,如 stackoverflow.com/a/58052624/2299084
【解决方案2】:

CMake先找到包:

find_package(Threads REQUIRED)

然后链接它:

target_link_libraries(${PROJECT_NAME} Threads::Threads)

现在构建将成功链接步骤。

【讨论】:

  • 最佳“现代”cmake 答案,谢谢!
【解决方案3】:

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

target_link_libraries(${PROJECT_NAME} pthread)

【讨论】:

  • 这还不够。您还必须设置编译器标志-pthread
【解决方案4】:

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

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

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

【讨论】:

  • 带有-pthread 标志?首先我听说了。您在哪里找到这些信息的?
  • 正如链接问题中的答案所述,您应该使用-pthread,而不是-lpthread。
【解决方案5】:

根据 CLion 2021.3.3,无需指定任何其他设置:

只需确保从 C 而不是 C++ 开始,然后选择 C ​​99。

--

cmake_minimum_required(VERSION 3.21)
project(threads01 C)

set(CMAKE_C_STANDARD 99)

add_executable(threads01 main.c)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 2016-08-21
    • 2018-03-25
    • 2018-04-07
    • 1970-01-01
    相关资源
    最近更新 更多