使用CMake链接到pthread库(在CLion中)

时间:2015-11-30 05:25:17

标签: c cmake pthreads

我看了一遍,我无法弄清楚如何让CLion链接lpthread库。我知道w / gcc你可以输入-lpthread,但我需要在CLion中做一些调试。

这是我目前的CMakeLists文件:

cmake_minimum_required(VERSION 3.3)

project(lab4)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

include_directories(/usr/include/)
link_directories(/usr/include/)

set(SOURCE_FILES lab4_v2.c)
add_executable(lab4 ${SOURCE_FILES})

5 个答案:

答案 0 :(得分:19)

你应该使用target_link_libraries

target_link_libraries(lab4 pthread)

答案 1 :(得分:17)

在CMake 2.8.12之前:

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 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_LIBES_INIT}")
endif()

如果你有CMake 3.1.0 +

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(my_app threads::Threads)

如果您想使用前两种方法中的一种使用CMake 3.1+,则需要:

set(THREADS_PREFER_PTHREAD_FLAG ON)

来自video of Anastasia Kazakova

的信息

答案 2 :(得分:12)

对于C:

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pthread")

答案 3 :(得分:1)

从CLion 2018.2开始的答案和捆绑的cmake版本3.12.0

我在该线程中使用了其他答案来修改我的CMakeLists.txt,最终发现我必须在set()中添加SECOND行才能完成此工作。我的文件如下所示:

cmake_minimum_required(VERSION 3.12)
project(thread_test_project C)

set(CMAKE_C_STANDARD 99)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pthread")

include_directories(.)

add_executable(thread_test
        thread_test.c)

答案 4 :(得分:0)

对于C ++ 使用

Feature: Login

  User should be able to login successfully after clicking login button.

  Scenario: User logs in successfully
    Given I expect the user enters email
    And I expect the user enters password
    When user hits Login button
    Then user should land on next screen