在 CMake header-only 库中生成 "stores" 它对 boost 文件系统的依赖

Generate in CMake header-only library that "stores" its dependency on boost filesystem

我想在 cmake 中从 header.h 生成一个 header-only 库,这取决于 libboost_system。 我可以毫无问题地编译库:

find_package(Boost COMPONENTS
        system filesystem
        REQUIRED)
include_directories(SYSTEM ${Boost_INCLUDE_DIRS})
add_library(mylib header.h)
target_link_libraries(mylib PUBLIC ${Boost_LIBRARIES})
set_target_properties(mylib PROPERTIES LINKER_LANGUAGE CXX)

但是当我link到别处的mylib时,它找不到带有ld错误的boost库。

失败是有道理的,但我不知道如何在CMake中解决它。 我如何 "store" 增强对 mylib 的依赖?这样我就不用担心在其他外部项目中找不到boost库了?

编辑:我正在使用 cmake 3.2

更新:mylib 是一个共享库 (.so),当我在其他项目中使用它时,linker 无法找到 boost 库:

target_link_libraries(newproject.exe ${external_mylib})

undefined reference to symbol '_ZN5boost6system15system_categoryEv'
/PATH/TO/libboost_system-mt-d.so.1.57.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status

如果我再次显式link到Boost_LIBRARIES就解决了。 target_link_libraries(newproject.exe ${external_mylib} ${Boost_LIBRARIES))

这也避免不了再次找到boost_libraries,也许解决办法是将boost_libraries放在环境变量LD_LIBRARY_PATH中? 那将是一个矫枉过正...

将您的 CMake 版本更新到 2.8.12 或更新版本。

您要找的功能是transitive dependency handling. It is toggled by the CMake policy CMP0022, so make sure you do not accidentally switch that off somewhere. Quoting from the manpage for target_link_libraries in CMake 3.1:

Library dependencies are transitive by default with this signature. When this target is linked into another target then the libraries linked to this target will appear on the link line for the other target too. This transitive “link interface” is stored in the INTERFACE_LINK_LIBRARIES target property and may be overridden by setting the property directly. When CMP0022 is not set to NEW, transitive linking is built in but may be overridden by the LINK_INTERFACE_LIBRARIES property. Calls to other signatures of this command may set the property making any libraries linked exclusively by this signature private.

顺便说一句,Boost.System is not the same as Boost.Filesystem。确保你确实 link 到正确的图书馆。

从您的编辑看来,您正在处理两个独立的 CMake 项目,这意味着您必须将 mylib 的依赖链转移到另一个项目。查看 CMake's packaging mechanism 了解如何操作。