【发布时间】:2018-02-20 03:40:49
【问题描述】:
我正在尝试使用 CMake 来查找外部库是否依赖于另一个库。
示例:HDF5 库可以选择与 zlib 链接 在 Linux 中,这可以通过
找到readelf -Ws /usr/local/lib/libhdf5.so | grep inflateEnd
54: 0000000000000000 0 FUNC GLOBAL DEFAULT UND inflateEnd
使用 CMake 似乎可以使用 CheckLibraryExists 找到它
https://cmake.org/cmake/help/v3.0/module/CheckLibraryExists.html
在 Cmake 脚本中
set(CMAKE_REQUIRED_LIBRARIES ${HDF5_LIBRARY})
check_library_exists(${HDF5_LIBRARY} inflateEnd "" NEED_ZLIB)
message(${NEED_ZLIB})
if (NEED_ZLIB)
message("-- ZLIB library is needed...")
else()
message("-- ZLIB library is not needed...")
endif()
找不到输出
-- Looking for inflateEnd in /usr/local/lib/libhdf5.so - not found
-- ZLIB library is not needed...
因此我做了使用 readelf 的 Cmake 版本,它找到了符号
但是,仍然想知道为什么上面的 Cmake 脚本会失败 :-)
工作版本是
set(have_read_symbols "no")
find_program(read_symbols_prg readelf)
if (${read_symbols_prg} MATCHES "readelf")
set(have_read_symbols "yes")
message("-- Readelf program found: " ${read_symbols_prg})
execute_process(COMMAND ${read_symbols_prg} -Ws ${HDF5_LIBRARY} OUTPUT_FILE ${CMAKE_CURRENT_BINARY_DIR}/symbols.txt)
endif()
if (${have_read_symbols} MATCHES "yes")
message("-- Detecting if HDF5 library ${HDF5_LIBRARY} needs the ZLIB library...")
file(STRINGS ${CMAKE_CURRENT_BINARY_DIR}/symbols.txt NEED_ZLIB REGEX "inflateEnd")
if (NEED_ZLIB)
message("${color_blue}-- ZLIB library is needed...${color_reset}")
else()
message("-- ZLIB library is not needed...")
endif(NEED_ZLIB)
endif()
找到符号
-- Detecting if HDF5 library /usr/local/lib/libhdf5.so needs the ZLIB library...
-- ZLIB library is needed...
【问题讨论】:
-
您可以查阅
CMakeError.log文件了解check_library_exists失败的原因。实际上,它尝试编译和链接包含函数调用的代码。我猜链接会导致“未定义的引用”,因为 hdf5 本身并没有定义inflateEnd函数,而是使用 zlib 中定义的函数。