Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined reference to pthread CLion

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.

like image 992
A. Lopez Avatar asked Aug 09 '17 22:08

A. Lopez


People also ask

Why am I getting Undefined reference to pthread_ create?

You are getting the reference error to pthread_create due to several reasons such as the pthread header file is missing, you are compiling a C program with GCC on Linux, and you are using the wrong compiler flag, or pthread is missing from your Integrated Development Environment.

How do I link pthread?

The proper way, when using pthreads, is to compile and link using the -pthread , which, among other things, will link in the pthread library. You have the -pthread flag for some of your executables, but not for others, and not for your clients.so library, so add the flag where required.

Where is pthread library in Linux?

The pthreads run time library usually lives in /lib, while the development library usually lives in /usr/lib.

How do I create a pthread?

pthread_t is the data type used to uniquely identify a thread. It is returned by pthread_create() and used by the application in function calls that require a thread identifier. The thread is created running start_routine, with arg as the only argument.


2 Answers

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)
like image 146
Le Danh Avatar answered Nov 15 '22 20:11

Le Danh


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.

like image 21
BullyWiiPlaza Avatar answered Nov 15 '22 21:11

BullyWiiPlaza