如何让CMake在Windows上静态链接pthread
?我使用MSYS2 MinGW 32 bit
和cmake
v3.7。
我想要实现的是像
这样的编译器调用g++ -static-libgcc -static-libstdc++ -std=c++11 -o test test.cpp -Wl,-Bstatic -lpthread
设置
target_link_libraries(test PUBLIC "-Wl,-Bstatic -lpthread")
导致-Wl,-Bdynamic -Wl,-Bstatic -lpthread
被调用。如果我更改CMAKE_EXE_LINKER_FLAGS
,则会在我的目标文件之前包含pthreads
,因此符号不会被解析。
答案 0 :(得分:1)
正如其源代码中提到的FindThreads.cmake
:
# For systems with multiple thread libraries, caller can set
#
# ::
#
# CMAKE_THREAD_PREFER_PTHREAD
#
# If the use of the -pthread compiler and linker flag is preferred then the
# caller can set
#
# ::
#
# THREADS_PREFER_PTHREAD_FLAG
#
# Please note that the compiler flag can only be used with the imported
# target. Use of both the imported target as well as this switch is highly
# recommended for new code.
因此,除了已经说过的内容之外,您可能还需要设置附加标志THREADS_PREFER_PTHREAD_FLAG
。在某些系统(OSX等)中,编译时需要此标志,因为如果只链接-lpthread
,它会定义一些丢失的宏。
set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
set(THREADS_PREFER_PTHREAD_FLAG TRUE)
add_library(test test.cpp)
set_property(TARGET test PROPERTY CXX_STANDARD 11)
set_target_properties(test PROPERTIES LINK_SEARCH_START_STATIC 1)
set_target_properties(test PROPERTIES LINK_SEARCH_END_STATIC 1)
set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++")
find_package(Threads REQUIRED)
target_link_libraries(test Threads::Threads)
有帮助吗?
答案 1 :(得分:0)
找到Threads模块:
find_package(Threads REQUIRED)
add_executable(myApp main.cpp)
target_link_libraries(myApp Threads::Threads)
请注意文档:
对于具有多个线程库的系统,调用者可以设置
CMAKE_THREAD_PREFER_PTHREAD