link to pthread library using CMake (in CLion)

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


For C:

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

Tags:

C

Pthreads

Cmake