Undefined reference to pthread CLion

Viewed 19184

I'm trying to run this simple thread c++ program in CLion

#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;
   }

My problem is that there's an error of undefined reference to pthread, and I don't undestand what I'm doing wrong... please notice that I'm doing this on CLion.

5 Answers

In CMake first find the package:

find_package(Threads REQUIRED)

Then link against it:

target_link_libraries(${PROJECT_NAME} Threads::Threads)

Now the build will succeed the linking step.

As per CLion 2021.3.3, no need to specify any additional settings:

Simply be sure to start from C and not C++ and select C 99.

--

cmake_minimum_required(VERSION 3.21)
project(threads01 C)

set(CMAKE_C_STANDARD 99)

add_executable(threads01 main.c)
Related