问题描述
我想创建一个依赖于另一个库的静态库,在本例中为ZLIB,为此我已经具有一个静态版本(libz.a)。
I would like to create a static library that depends on another library, in this case ZLIB, for which I already have a static build (libz.a).
我有以下内容:
...
set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static")
set (BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE)
set (CMAKE_FIND_LIBRARY_SUFFIXES .a ${CMAKE_FIND_LIBRARY_SUFFIXES}) # to find the .a instead of the .so
...
find_package(ZLIB REQUIRED)
if (ZLIB_FOUND)
message(STATUS "ZLIB library: ${ZLIB_LIBRARIES}") # ZLIB library: /usr/lib64/libz.a
include_directories(${ZLIB_INCLUDE_DIRS})
set (EXT_LIBS ${EXT_LIBS} ${ZLIB_LIBRARIES})
endif()
...
add_library (libTest ${MCCORE_SOURCES_CC})
target_link_libraries(libTest ${EXT_LIBS}) #EXT_LIBS = /usr/lib64/libz.a
但是,最后一个构建的步骤是创建静态库,但未引用 / usr / l ib64 / libz.a
However, the final step of the build is creating the static library but without any reference to /usr/lib64/libz.a
ex:
/usr/bin/ar cr libTest.a object1.o object2.o ... objectN.o
我希望:
/usr/bin/ar cr libTest.a object1.o object2.o ... objectN.o /usr/lib64/libz.a
似乎最终的归档创建并没有照顾使用 target_link_libraries
设置的库。
It seems the final archive creation doesn't care for libraries set with target_link_libraries
.
有什么想法吗?
我该怎么办?
推荐答案
在Windows(使用Visual Studio)下,可以完成以下操作:
Under Windows (with Visual Studio) the following would do the trick:
add_library(fooStatic1 STATIC fooStatic.cpp)
set(LIBS_TO_COMBINE "${CMAKE_BINARY_DIR}/libfooStatic1.lib ${ZLIB_LIBRARIES}")
add_library(combined STATIC ${LIBS_TO_COMBINE} dummy.cpp) #dummy.cpp being empty
add_dependencies(combined fooStatic1)
set_source_files_properties(${LIBS_TO_COMBINE} PROPERTIES EXTERNAL_OBJECT TRUE GENERATED TRUE)
set_target_properties(combined PROPERTIES LINKER_LANGUAGE CXX)
set_target_properties(combined PROPERTIES STATIC_LIBRARY_FLAGS "${LIBS_TO_COMBINE}")
不幸的是,它赢了'不能在linux下工作,因为 ar
只会合并存档文件而不会将它们解包-产生的东西实际上并不可用。为了实现您的目标,您需要提取 .o
文件并重新组合它们:
Unfortunately, it won't work under linux, as ar
will just combine the archive files without unpacking them - creating something that is not really usable. In order to achieve your goal you need to extract the .o
files and recombine them:
ar -x /usr/lib64/libz.a
ar -x libfooStatic1.a
ar -rc libcombined.a *.o
我不知道 CMake
宏在此过程中会有所帮助。您可能在 execute_process(...)
中运行 ar -x
,对输出进行glob,然后运行 ar -rc
。
I am not aware of a CMake
macro that would help in the process. You could probably run ar -x
in execute_process(...)
, glob the output, and then run ar -rc
.
这篇关于创建引用其他静态库的静态库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!