用cmake静态链接pthread [英] link pthread statically with cmake

查看:1264
本文介绍了用cmake静态链接pthread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Windows上让CMake静态链接 pthread ?我使用的是 MSYS2 MinGW 32位 cmake v3.7。

How can I get CMake to link pthread statically on Windows? I use MSYS2 MinGW 32 bit and cmake v3.7.

我想实现的是一个编译器调用,例如

What I would like to achieve is a compiler invocation like

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 ,因此无法解析符号。

results in -Wl,-Bdynamic -Wl,-Bstatic -lpthread being called. If I change CMAKE_EXE_LINKER_FLAGS, pthreads is included before my object files and thus symbols are not resolved.

推荐答案

正如 FindThreads.cmake 在其源代码中提到的那样:

As the FindThreads.cmake mention in its source code:

# 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 时将丢失的宏。

So in addition to what already said, you might need to set the additional flag THREADS_PREFER_PTHREAD_FLAG. In some systems (OSX, etc.) this flag is needed at compilation time because it defines some macros that would be missing if you would only link -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)  

有帮助吗?

这篇关于用cmake静态链接pthread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆