Answers:
@Manuel在那儿。您也可以添加编译器选项,如下所示:
如果您拥有CMake 3.1.0+,这将变得更加容易:
set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(my_app PRIVATE Threads::Threads)
如果您使用的是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_LIBS_INIT}")
endif()
较旧的CMake版本可能需要:
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()
如果要在CMake 3.1+中使用前两种方法之一,则也需要使用set(THREADS_PREFER_PTHREAD_FLAG ON)
。
NOT CMAKE_HAVE_THREADS_LIBRARY
),例如在Ubuntu 15.04上,例如CMake 3.0.2似乎不会设置THREADS_HAVE_PTHREAD_ARG
/usr/share/cmake-2.8/Modules/FindThreads.cmake
(例如,请参见apt-browse.org/browse/ubuntu/trusty/main/all/cmake-data/…)基本上,THREADS_HAVE_PTHREAD_ARG
(即,如果标志的其它变型均未发现仅设置-lpthread
,-lpthread
或-lthread
)
以下内容应该是干净的(使用find_package
)并且可以正常工作(将find模块称为FindThreads
):
cmake_minimum_required (VERSION 2.6)
find_package (Threads)
add_executable (myapp main.cpp ...)
target_link_libraries (myapp ${CMAKE_THREAD_LIBS_INIT})
这是正确的答案:
ADD_EXECUTABLE(your_executable ${source_files})
TARGET_LINK_LIBRARIES( your_executable
pthread
)
相当于
-lpthread
target_link_libraries(target "$<$<CXX_COMPILER_ID:GNU>:-pthread>$<$<CXX_COMPILER_ID:Clang>:-pthreads>")
至少基于目标并且在Windows和其他平台上不会失败的东西。