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.
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.
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.
The pthreads run time library usually lives in /lib, while the development library usually lives in /usr/lib.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With