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

标签 c++ boost linker cmake

我想在 cmake 中从 header.h 生成一个仅包含 header 的库,它依赖于 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)

但是当我在其他地方链接到 mylib 时,它找不到带有 ld 错误的 boost 库。

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

编辑:我正在使用 cmake 3.2

更新:mylib 是一个共享库 (.so),当我在其他项目中使用它时,链接器无法找到 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

如果我再次显式链接到 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 .它由 CMake 策略 CMP0022 切换,因此请确保您不会在某处不小心将其关闭。引用自 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.SystemBoost.Filesystem 不同.确保您实际链接到正确的库。

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

关于c++ - 在 CMake header-only library 中生成 "stores"它对 boost 文件系统的依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28803757/

相关文章:

c++ - ubuntu上安装qtservice

c++ - SDL2 图像到屏幕问题

c++ - 在 Obj-C 项目中嵌入 Prolog 引擎

ios - 构建存档时 AKTabBarController 不起作用

c++ - 使用 C++ 库时如何避免包含相同的代码?

c++ - 如何使用 GCC 12.1 生成 C++23 堆栈跟踪?

c++ - Boost.Geometry Correct() 失败

c++ - Boost::Asio 同步客户端超时

c++ - 具有 C++ Boost 线程的体系结构 x86_64 的 undefined symbol

c++ - 链接到 boost_thread 的问题