Reputation: 91
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.
Upvotes: 9
Views: 20039
Reputation: 11666
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)
Upvotes: 0
Reputation: 19233
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.
Upvotes: 5
Reputation: 403
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)
Upvotes: 25
Reputation: 4409
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.
Upvotes: 0
Reputation: 104
Make sure you are linking to pthread in the end of your CMakeLists.txt
target_link_libraries(${PROJECT_NAME} pthread)
Upvotes: 0