C语言 使用 CMake 链接到 pthread 库(在 CLion 中)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33991918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
link to pthread library using CMake (in CLion)
提问by somecbusnerd
I've looked all over and I can't figure out how to get CLion to link the lpthread library. I know that w/ gcc you can just type -lpthread, but I need to do some debugging in CLion.
我已经看遍了,我无法弄清楚如何让 CLion 链接 lpthread 库。我知道 w/gcc 你可以只输入 -lpthread,但我需要在 CLion 中进行一些调试。
Here's my current CMakeLists file:
这是我当前的 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})
回答by kroiz
Before CMake 2.8.12:
在 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()
If you have CMAKE 2.8.12+:
如果您有 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()
If you have CMake 3.1.0+
如果你有 CMake 3.1.0+
set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(my_app Threads::Threads)
If you want to use one of the first two methods with CMake 3.1+, you will need:
如果要在 CMake 3.1+ 中使用前两种方法之一,则需要:
set(THREADS_PREFER_PTHREAD_FLAG ON)
Info taken from video by Anastasia Kazakova
回答by Chris Maes
回答by snr
For C:
对于 C:
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pthread")
回答by copeland3300
Answer as of CLion 2018.2 and the bundled cmake version of 3.12.0
从 CLion 2018.2 和 3.12.0 的捆绑 cmake 版本开始回答
I used other answers in this thread to modify my CMakeLists.txt, and ultimately found I had to add a SECOND line with set() to make this work. My file looks like the following:
我在这个线程中使用了其他答案来修改我的 CMakeLists.txt,最终发现我必须用 set() 添加第二行才能完成这项工作。我的文件如下所示:
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)
回答by dklovedoctor
For C++ use
对于 C++ 使用
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -pthread" )

