'What is the proper use of CMake FindThreads with modern C++?
The source for the CMake (https://github.com/Kitware/CMake/blob/master/Modules/FindThreads.cmake) claims the following about the "FindThreads" functionality:
This module is not needed for C++11 and later if threading is done using
std::thread
from the standard library.
But if I follow this advice (on my Mint18 x86_64 system, gcc8, CMake 3.13.2) I get:
/usr/bin/ld: CMakeFiles/prism-esm-dummy.dir/src/main.cpp.o: undefined reference to symbol 'pthread_create@@GLIBC_2.2.5'
//lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
If the module is exercised (as best I could figure using other SO articles and previously given advice):
set (THREADS_PREFER_PTHREAD_FLAG ON)
find_package (Threads REQUIRED)
add_executable(my_app main.cpp)
target_link_libraries (my_app Threads::Threads)
... the result is the same.
THREADS_FOUND
is true
and CMAKE_USE_PTHREADS_INIT
is 1
, but i get no -pthread
under compile, or a -lpthread
during link. I checked a number of other variables mentioned in the module, and all I tried were not set.
Is there a correct way to do this? Or should I just use the normal flags and move on with my life?
Solution 1:[1]
find_package( Threads )
target_link_libraries( ${PROJECT_NAME} ${CMAKE_THREAD_LIBS_INIT} )
Solution 2:[2]
I try to give a more complete answer, since I struggled a bit implementing what was suggested above
Create a new folder
mkdir test_project
cd test_project
First of all you will need to create a test.cpp
with:
touch test.cpp
and then paste in the file the following:
#include <iostream>
int main(int argc, char** argv){
std::cout << "Hello World" << std::endl;
return 0;
}
in your CMakeLists.txt you should have something like the following:
project("test_proj")
cmake_minimum_required (VERSION 2.4) # this depends on what you are testing
find_package(Threads)
add_executable(test test.cpp)
target_link_libraries( test ${CMAKE_THREAD_LIBS_INIT} )
I hope this answer helps someone with the same problem.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Felix Xu |
Solution 2 | desmond13 |