23

I've looked all over and I can't figure out how to get CLion to link the lpthread library. I know that w/ gcc you can just type -lpthread, but I need to do some debugging in CLion.

Here's my current CMakeLists file:

cmake_minimum_required(VERSION 3.3)

project(lab4)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

include_directories(/usr/include/)
link_directories(/usr/include/)

set(SOURCE_FILES lab4_v2.c)
add_executable(lab4 ${SOURCE_FILES})
Chris Maes
  • 35,025
  • 12
  • 111
  • 136
dcgenjin
  • 1,108
  • 3
  • 12
  • 25

5 Answers5

33

Before CMake 2.8.12:

find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
  set_property(TARGET my_app PROPERTY COMPILE_OPTIONS "-pthread")
  set_property(TARGET my_app PROPERTY INTERFACE_COMPILE_OPTIONS "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
  target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()

If you have CMAKE 2.8.12+:

find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
  target_compile_options(my_app PUBLIC "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
  target_link_libraries(my_app "${CMAKE_THREAD_LIBES_INIT}")
endif()

If you have CMake 3.1.0+

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(my_app Threads::Threads)

If you want to use one of the first two methods with CMake 3.1+, you will need:

set(THREADS_PREFER_PTHREAD_FLAG ON)

Info taken from video by Anastasia Kazakova

A-n-t-h-o-n-y
  • 410
  • 6
  • 14
kroiz
  • 1,722
  • 1
  • 27
  • 43
25

For C:

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pthread")
21

you should use target_link_libraries:

target_link_libraries(lab4 pthread)
Chris Maes
  • 35,025
  • 12
  • 111
  • 136
4

For C++ use

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -pthread" )
dklovedoctor
  • 548
  • 1
  • 5
  • 8
3

Answer as of CLion 2018.2 and the bundled cmake version of 3.12.0

I used other answers in this thread to modify my CMakeLists.txt, and ultimately found I had to add a SECOND line with set() to make this work. My file looks like the following:

cmake_minimum_required(VERSION 3.12)
project(thread_test_project C)

set(CMAKE_C_STANDARD 99)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pthread")

include_directories(.)

add_executable(thread_test
        thread_test.c)
copeland3300
  • 581
  • 7
  • 11