linux - 使用 CMake 在库中查找符号

标签 linux cmake zlib hdf5

我正在尝试使用 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...

最佳答案

好的,checkLibraryExists() 的 Cmake 文档没有详细说明如何完成此操作,他们只是说“检查函数是否存在”。 checkLibraryExists() 尝试链接测试程序,并根据成功与否,将输出变量参数设置为值 1 或空。

在这种情况下,要查看的符号必须是在 libhdf5.so 中定义的符号,并且只能使用 zlib 库。这种情况下只有一个符号,即根据 zlib 情况下的 #ifdef 添加到库中的名为“H5Z_DEFLATE”的结构。

所以,这就成功了

check_library_exists(${HDF5_LIBRARY} H5Z_DEFLATE "" NEED_ZLIB)

然而,对于使用 Visual Studio 的 Windows 情况,这很容易出错,因为要检测到 check_library_exists(),Visual Studio 必须设置一个选项作为 zlib 库的附加依赖项,而这不是成功构建库的必要条件.因此,如果设置了此选项,check_library_exists 会检测依赖项,如果未设置,则不会。

关于linux - 使用 CMake 在库中查找符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46163459/

相关文章:

Linux 查找特定年份后创建的 : How to find . PDF 文件?

c++ - 这个程序的输出是什么?

javascript - 将数据从 Python 脚本发送到浏览器(在 Linux 上的 xserver 下)

linux - 在 SLES 12-SP2 x86_64 上构建 openssl 1.0.2p 失败

c++ - 如何要求CMake不冗长?

cmake - 使用 CMAKE 将字符串拆分为列表的常用方法是什么?

c++ - 运行在同一台机器上编译的程序时 GLIBCXX 版本错误

ruby - Zlib 在新的 ubuntu server/rvm/gemset 中不断引起问题

python - 如何在json中转储压缩字符串?

javascript - Node.js:tcp 连接中的 zlib 压缩