I want to statically compile my program against another static library, for this example I'm using zeromq. Here is my 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} )
It finds the .a
file when I run mkdir build && cd build && cmake ..
-- /usr/local/lib/libzmq.a
However, if I examine the link.txt
file, the library is dynamically linked:
/usr/bin/c++ CMakeFiles/test.dir/test.cpp.o \
-o test -rdynamic /usr/local/lib/libzmq.a
The weird bit is that if I move the file to a different directory, say /usr/lib
and run cmake ..
once more, it locates the new path to the library:
-- /usr/lib/libzmq.a
But now it has magically changed to static linking:
/usr/bin/c++ CMakeFiles/test.dir/test.cpp.o \
-o test -rdynamic -Wl,-Bstatic -lzmq -Wl,-Bdynamic
The same thing applies to other libraries I'm linking to.
Why are all my libraries in /usr/local/lib
being dynamically linked?
答案 0 :(得分:4)
你不应该直接使用路径,而是创建一个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:
如果目标不是静态库,请确保链接 类型是共享的。这是因为动态模式链接可以处理 共享库和静态库,但静态模式只能处理 静态库。如果先前的用户项目将链接类型更改为 我们需要确保它回归共享。
基本上,如果当前处于动态模式,它会让链接器处理检测到库是静态的。
答案 1 :(得分:1)
关于/usr/local/lib
和/usr/lib
之间区别的原始问题的答案是,默认情况下,/usr/local/lib
不是隐式链接目录之一。因此,快速解决方法是在配置中包含此行:
set(CMAKE_CXX_IMPLICIT_LINK_DIRECTORIES /usr/local/lib ${CMAKE_CXX_IMPLICIT_LINK_DIRECTORIES})
但是,正如本other answer所指出的那样,直接引用文件不是一种方法,而应该使用add_library
。