我运行RHEL 5.1并使用gcc。

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


下面是正确答案:

ADD_EXECUTABLE(your_executable ${source_files})

TARGET_LINK_LIBRARIES( your_executable
pthread
)

相当于

-lpthread

下面应该是clean(使用find_package)和work (find模块称为FindThreads):

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

@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)。


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

Use:

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

OR

target_link_libraries(XXX公共线程)

OR

set_target_properties(XXX属性)