cmake和libpthread

时间:2009-10-25 13:25:50

标签: pthreads cmake

我正在使用RHEL 5.1并使用gcc

我如何告诉cmake-pthread添加到编译和链接中?

4 个答案:

答案 0 :(得分:176)

以下内容应该是干净的(使用find_package)和work(查找模块称为FindThreads):

cmake_minimum_required (VERSION 2.6) 
find_package (Threads)
add_executable (myapp main.cpp ...)
target_link_libraries (myapp ${CMAKE_THREAD_LIBS_INIT})

答案 1 :(得分:145)

@Manuel是那里的一部分。您也可以添加编译器选项,如下所示:

如果你有CMake 3.1.0 +,this becomes even easier

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(my_app 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)

答案 2 :(得分:13)

这是正确的回答:

ADD_EXECUTABLE(your_executable ${source_files})

TARGET_LINK_LIBRARIES( your_executable
pthread
)

相当于

-lpthread

答案 3 :(得分:3)

target_compile_options 上面的解决方案是错误的,它不会链接库。

使用:

SET(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -pthread")

target_link_libraries(XXX PUBLIC pthread)

set_target_properties(XXX PROPERTIES LINK_LIBRARIES -pthread)