我对 cmake FindThreads 进行了测试。这是我的源代码test.cpp和CMakeLists.txt:
#include <pthread.h>
void* test_func(void* data)
{
return data;
}
int main(void)
{
pthread_t thread;
pthread_create(&thread, NULL, test_func, NULL);
pthread_detach(thread);
pthread_cancel(thread);
pthread_join(thread, NULL);
pthread_atfork(NULL, NULL, NULL);
pthread_exit(NULL);
return 0;
}
cmake_minimum_required(VERSION 3.5)
project(test C CXX)
set(CMAKE_THREAD_PREFER_PTHREAD ON)
set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
add_executable(test test.cpp)
if(TARGET Threads::Threads)
target_link_libraries(test PRIVATE Threads::Threads)
endif()
当我跑步时:
cmake .
我得到输出:
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD - Failed
-- Check if compiler accepts -pthread
-- Check if compiler accepts -pthread - yes
-- Found Threads: TRUE
然后我检查CMakeError.txt,发现:
gmake[1]: Entering directory '/home/hye/tmp/cmake-error/CMakeFiles/CMakeTmp'
Building C object CMakeFiles/cmTC_55ab6.dir/src.c.o
/usr/bin/clang -DCMAKE_HAVE_LIBC_PTHREAD -o CMakeFiles/cmTC_55ab6.dir/src.c.o -c /home/hye/tmp/cmake-error/CMakeFiles/CMakeTmp/src.c
Linking C executable cmTC_55ab6
/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_55ab6.dir/link.txt --verbose=1
/usr/bin/clang -DCMAKE_HAVE_LIBC_PTHREAD CMakeFiles/cmTC_55ab6.dir/src.c.o -o cmTC_55ab6
/usr/bin/ld: CMakeFiles/cmTC_55ab6.dir/src.c.o: in function `main':
src.c:(.text+0x35): undefined reference to `pthread_create'
/usr/bin/ld: src.c:(.text+0x41): undefined reference to `pthread_detach'
/usr/bin/ld: src.c:(.text+0x4d): undefined reference to `pthread_cancel'
/usr/bin/ld: src.c:(.text+0x5f): undefined reference to `pthread_join'
clang-9: error: linker command failed with exit code 1 (use -v to see invocation)
gmake[1]: *** [CMakeFiles/cmTC_55ab6.dir/build.make:107: cmTC_55ab6] Error 1
gmake[1]: Leaving directory '/home/hye/tmp/cmake-error/CMakeFiles/CMakeTmp'
gmake: *** [Makefile:141: cmTC_55ab6/fast] Error 2
我的问题是为什么执行测试 CMAKE_HAVE_LIBC_PTHREAD - 失败,既然失败了,就这样做
真的找到了线程,我完全困惑了。感谢您的回复!