How do I force cmake to include "-pthread" option during compilation?

GccBuildBuild AutomationCmake

Gcc Problem Overview


I know there is something like find_package(Threads) but it doesn't seem to make a difference (at least by itself). For now I'm using SET(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "-pthread"), but it doesn't look like a correct solution to me.

Gcc Solutions


Solution 1 - Gcc

The Threads module in the latest versions (>= 3.1) of CMake generates the Threads::Threads imported target. Linking your target against Threads::Threads adds all the necessary compilation and linking flags. It can be done like this:

set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
set(THREADS_PREFER_PTHREAD_FLAG TRUE)
find_package(Threads REQUIRED)

add_executable(test test.cpp)
target_link_libraries(test Threads::Threads)

Use of the imported target is highly recommended for new code, according to the CMake docs

Solution 2 - Gcc

find_package( Threads ) calls a CMake module that first, searches the file system for the appropriate threads package for this platform, and then sets the CMAKE_THREAD_LIBS_INIT variable (and some other variables as well). It does not tell CMake to link any executables against whatever threads library it finds. You tell CMake to link you executable against the "Threads" library with the target_link_libraries() command. So, for example lets say your program is called test. To link it against threads you need to:

find_package( Threads )
add_executable( test test.cpp )
target_link_libraries( test ${CMAKE_THREAD_LIBS_INIT} )

Solution 3 - Gcc

How about the following:

set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
find_package(Threads REQUIRED)
if(CMAKE_USE_PTHREADS_INIT)
    set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "-pthread")
elseif(...)
    ...
endif()
add_executable( test test.cpp )
target_link_libraries( test ${CMAKE_THREAD_LIBS_INIT} )

Solution 4 - Gcc

If I explicitly specify the default entry point and the library to use, it compiles without problems. The default entry point here is to specify the version in cmake. cmake_minimum_required(...), target_link_libraries(...) Below is an example.

# important
cmake_minimum_required(VERSION 2.8)

project(main)

# set c++ version & etc...
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# important
find_package( Threads )

add_executable(main main.cpp)

# important
target_link_libraries(main ${CMAKE_THREAD_LIBS_INIT})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTomasz GrobelnyView Question on Stackoverflow
Solution 1 - GccAlex CheView Answer on Stackoverflow
Solution 2 - GccltcView Answer on Stackoverflow
Solution 3 - Gccuser3701085View Answer on Stackoverflow
Solution 4 - GccromulusView Answer on Stackoverflow