9

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.

Jonathan
  • 6,507
  • 5
  • 37
  • 47
A. Lopez
  • 91
  • 1
  • 1
  • 3

5 Answers5

25

In CLion, to compile with flag -pthread you should add the following line to CMakeLists.txt (I've tested and it works):

SET(CMAKE_CXX_FLAGS -pthread)
Le Danh
  • 403
  • 4
  • 8
  • 1
    It worked for me but I also had to add `find_package(Threads)`. – Paul Laffitte Apr 20 '18 at 20:24
  • @PaulLaffitte It worked for me without having to add `find_package(Threads)` – Abdelrahman Shoman Feb 16 '20 at 13:52
  • I downvoted not because this is a bad answer, it was ok at the time of writing. However, best practice is now to use `find_package(…)` and link against `Threads::Threads` as in https://stackoverflow.com/a/58052624/2299084 – flaviut May 22 '20 at 22:32
5

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.

BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185
0

You have to compile with flag -lpthread or -pthread (its usually advised to usepthread). If you're using CLion then you will need to edit CMakeLists.txt to ensure that your code is compiled with this flag by setting compiler flags with a command like:

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

You can learn more about these options on this post.

Jon Deaton
  • 3,943
  • 6
  • 28
  • 41
  • with `-pthread` flag? First I hear about that. Where you found that information? – S.R Aug 09 '17 at 22:54
  • I learned about it here https://stackoverflow.com/questions/23250863/difference-between-pthread-and-lpthread-while-compiling – Jon Deaton Aug 09 '17 at 22:55
  • 1
    As the answer in the linked question states, you should use -pthread, not -lpthread. – MikeMB Aug 09 '17 at 23:36
0

Make sure you are linking to pthread in the end of your CMakeLists.txt

target_link_libraries(${PROJECT_NAME} pthread)
Nate M
  • 96
  • 2
0

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)
ingconti
  • 10,876
  • 3
  • 61
  • 48