I'm running RHEL 5.1 and use gcc.
How I tell cmake to add -pthread to compilation and linking?
I'm running RHEL 5.1 and use gcc.
How I tell cmake to add -pthread to compilation and linking?
@Manuel was part way there. You can add the compiler option as well, like this:
If you have CMake 3.1.0+, this becomes even easier:
set(THREADS_PREFER_PTHREAD_FLAG ON) find_package(Threads REQUIRED) target_link_libraries(my_app PRIVATE Threads::Threads) If you are using CMake 2.8.12+, you can simplify this to:
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_LIBS_INIT}") endif() Older CMake versions may require:
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 want to use one of the first two methods with CMake 3.1+, you will need set(THREADS_PREFER_PTHREAD_FLAG ON) there too.
NOT CMAKE_HAVE_THREADS_LIBRARY), e.g. on Ubuntu 15.04 :(/usr/share/cmake-2.8/Modules/FindThreads.cmake (eg. see here apt-browse.org/browse/ubuntu/trusty/main/all/cmake-data/…) Basically, THREADS_HAVE_PTHREAD_ARG is only set if the other variations of the flag weren't found (ie. -lpthread, -lpthread, or -lthread)The following should be clean (using find_package) and work (the find module is called FindThreads):
cmake_minimum_required (VERSION 2.6) find_package (Threads) add_executable (myapp main.cpp ...) target_link_libraries (myapp ${CMAKE_THREAD_LIBS_INIT}) find_package also the approch on windows for .dll dependencies? Because usually, you have your lib dependencies in a thirdParty directory... but cmake looks in a IMPORTED_LOCATION path, isn't it?Here is the right anwser:
ADD_EXECUTABLE(your_executable ${source_files}) TARGET_LINK_LIBRARIES( your_executable pthread ) equivalent to
-lpthread target_link_libraries(target "$<$<CXX_COMPILER_ID:GNU>:-pthread>$<$<CXX_COMPILER_ID:Clang>:-pthreads>") which is at least target-based and doesn't fail on Windows and other platforms.target_compile_options solution above is wrong, it won't link the library.
Use:
SET(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -pthread")
OR
target_link_libraries(XXX PUBLIC pthread)
OR
set_target_properties(XXX PROPERTIES LINK_LIBRARIES -pthread)
find_package(Threads) and target_link_libraries(my_app PRIVATE Threads::Threads) instead.