共享库的 CMake 和命令依赖链接 [英] CMake and order dependent linking of shared libraries

查看:19
本文介绍了共享库的 CMake 和命令依赖链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一些小组件作为主应用程序的共享库.让我们以 libalibb 为例.每个都构建在自己的子目录中,如下所示:

I have a few small components that I am building as shared libraries for my main application. Lets use an example of liba and libb. Each is built within their own subdirectory as follows:

add_library(liba SHARED a.cpp)

然后,在根项目文件夹中,我需要将我的主应用程序链接到两者.

Then, in the root project folder, I need to link my main application to both.

include_directories(a)
include_directories(b)
add_executable(dummy dummy.cpp)
target_link_libraries(dummy a b)

CMake 运行良好,我的应用程序编译但无法链接.问题是 b 引用了 a.如果我在链接时提供库的顺序

CMake runs fine with this, and my application compiles but fails to link. The problem is that b references a. If I supply the order of the libraries while linking as

target_link_libraries(dummy b a)

程序编译和链接正常

当这种系统开始涉及更复杂的库相互依赖时,即使依赖是非循环的,它也开始变得不可能.我如何管理此处的链接步骤?在 CMake 中订购链接库有什么技巧吗?

When this sort of system starts involving more complex inter dependency of the libraries, it starts to be impossible even if the dependencies are acyclic. How do I manage the linking step here? Is there a trick to ordering libraries for linking in CMake?

推荐答案

可以通过添加

target_link_libraries(b a)


来自文档:

库依赖项默认是可传递的.当这个目标链接到另一个目标时,链接到这个目标的库也会出现在另一个目标的链接线上.

Library dependencies are transitive by default. 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.

所以,如果你以这种方式指定a作为b的依赖,你甚至不需要显式列出a任何依赖于 b 的目标,即你的其他命令可以是:

So, if you specify a as a dependency of b in this way, you don't even need to explicitly list a in any target which depends on b, i.e. your other command can be just:

target_link_libraries(dummy b)

尽管列出 a 也不会造成任何伤害.

although it wouldn't do any harm to list a as well.

这篇关于共享库的 CMake 和命令依赖链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆