gpt4 book ai didi

c++ - CMake动态链接 `.a`中的 `/usr/local/lib`文件

转载 作者:行者123 更新时间:2023-12-01 19:31:18 24 4
gpt4 key购买 nike

我想针对另一个静态库静态编译我的程序,在本例中我使用 Zeromq。这是我的 CMakeLists.txt

cmake_minimum_required(VERSION 2.6)
add_executable( test test.cpp )
find_library(ZMQ NAMES libzmq.a)
message(STATUS ${ZMQ})
target_link_libraries( test ${ZMQ} )

当我运行 mkdir build && cd build && cmake .. 时,它会找到 .a 文件

-- /usr/local/lib/libzmq.a

但是,如果我检查 link.txt 文件,该库是动态链接的:

/usr/bin/c++ CMakeFiles/test.dir/test.cpp.o \
-o test -rdynamic /usr/local/lib/libzmq.a

奇怪的是,如果我将文件移动到另一个目录,例如 /usr/lib 并再次运行 cmake ..,它会找到新路径到图书馆:

-- /usr/lib/libzmq.a

但现在它神奇地变成了静态链接:

/usr/bin/c++ CMakeFiles/test.dir/test.cpp.o \
-o test -rdynamic -Wl,-Bstatic -lzmq -Wl,-Bdynamic

同样的事情也适用于我链接到的其他库。

为什么我在 /usr/local/lib 中的所有库都是动态链接的?

最佳答案

您不应直接使用该路径,而应创建 imported target相反,您可以显式地将其声明为静态:

cmake_minimum_required(VERSION 2.6)
add_executable( test test.cpp )

find_library(zmq_location NAMES libzmq.a)
message(STATUS ${zmq_location})

add_library(zmq STATIC IMPORTED)
set_target_properties(zmq PROPERTIES IMPORTED_LOCATION ${zmq_location})

target_link_libraries( test zmq )

这可能会导致库看起来是动态链接的,但cmake source code has the answer :

If the target is not a static library make sure the link type is shared. This is because dynamic-mode linking can handle both shared and static libraries but static-mode can handle only static libraries. If a previous user item changed the link type to static we need to make sure it is back to shared.

本质上,它让链接器处理检测库是否是静态的(如果当前处于动态模式)。

关于c++ - CMake动态链接 `.a`中的 `/usr/local/lib`文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39249421/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com