C++ 如何让 CMake 在 Ubuntu 上识别 pthread?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15193785/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:09:23  来源:igfitidea点击:

How to get CMake to recognize pthread on Ubuntu?

c++pthreadscmakeubuntu-12.10

提问by Stéphane

If I compile on the command-line with g++ directly, I can see everything I need is there:

如果我直接在命令行上用 g++ 编译,我可以看到我需要的一切都在那里:

$ g++ -pthread test.cpp
$ ldd a.out
    linux-vdso.so.1 =>  (0x00007fffd05b3000)
    libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f4a1ba8d000)
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f4a1b870000)
    ...more...

Then I try to create a simple cmake file for this 5-line test app:

然后我尝试为这个 5 行测试应用程序创建一个简单的 cmake 文件:

$ cat CMakeLists.txt 
PROJECT ( Test CXX )
CMAKE_MINIMUM_REQUIRED ( VERSION 2.8 )
FIND_PACKAGE ( Threads REQUIRED )
ADD_EXECUTABLE ( test test.cpp )
TARGET_LINK_LIBRARIES ( test ${CMAKE_THREAD_LIBS_INIT} )

However, I cannot figure out why CMake doesn't find what it needs to use for Threads:

但是,我无法弄清楚为什么 CMake 找不到它需要用于的内容Threads

$ cd build/
$ cmake ..
CMake Error at /usr/share/cmake-2.8/Modules/FindPackageHandleStandardArgs.cmake:97 (MESSAGE):
  Could NOT find Threads (missing: Threads_FOUND)
Call Stack (most recent call first):
  /usr/share/cmake-2.8/Modules/FindPackageHandleStandardArgs.cmake:288 (_FPHSA_FAILURE_MESSAGE)
  /usr/share/cmake-2.8/Modules/FindThreads.cmake:166 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
  CMakeLists.txt:4 (FIND_PACKAGE)
-- Configuring incomplete, errors occurred!

回答by Stéphane

Oh, this was was a pain! I probably lost 2 hours on this. Here is the solution:

哦,这是一种痛苦!我可能为此浪费了 2 个小时。这是解决方案:

CMake uses short 'C' applications to test/try things. If the CMakeLists.txt states that C++ is used for the project, without also listing C, then some of those shorts tests incorrectly fail, and cmake then thinks those things aren't found.

CMake 使用简短的“C”应用程序来测试/尝试。如果 CMakeLists.txt 声明项目使用了 C++,而没有列出 C,那么其中一些 shorts 测试错误地失败了,然后 cmake 认为没有找到这些东西。

The solution was to change the first line of CMakeLists from this:

解决方案是从此更改 CMakeLists 的第一行:

PROJECT ( Test CXX )

...to include C as a language:

...将 C 作为一种语言包括在内:

PROJECT ( Test C CXX )

Then delete build, recreate it, and everything then works:

然后删除build,重新创建它,然后一切正常:

rm -rf build
mkdir build
cd build
cmake ..