通过链接同一个库两次来解决循环依赖性? [英] Resolving circular dependencies by linking the same library twice?

查看:659
本文介绍了通过链接同一个库两次来解决循环依赖性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个代码库分解成静态库。不幸的是,库有循环依赖;例如 libfoo.a 取决于 libbar.a ,反之亦然。

We have a code base broken up into static libraries. Unfortunately, the libraries have circular dependencies; e.g., libfoo.a depends on libbar.a and vice-versa.

我知道正确的处理方式是使用链接器的 - start-group - end- group 选项,如下所示:

I know the "correct" way to handle this is to use the linker's --start-group and --end-group options, like so:

g++ -o myApp -Wl,--start-group -lfoo -lbar -Wl,--end-group

但是在我们现有的Makefiles中,处理方式如下:

But in our existing Makefiles, the problem is typically handled like this:

g++ -o myApp -lfoo -lbar -lfoo

(假设这扩展到〜20个具有复杂相互依赖关系的库。)

(Imagine this extended to ~20 libraries with complex interdependencies.)

我们的Makefiles将第二种形式改为第一种形式,但现在我的同事问我为什么...除了因为它更清洁和一个模糊的感觉,另一种形式是有风险的,我没有一个好的答案。

I have been going through our Makefiles changing the second form to the first, but now my co-workers are asking me why... And other than "because it's cleaner" and a vague sense that the other form is risky, I do not have a good answer.

因此,可以多次链接同一个库有时会造成问题吗?例如,如果相同的.o被拉入两次,链接是否会与多重定义的符号失败?或者有任何风险,我们可以结束同一个静态对象的两个副本,创建微妙的错误?

So, can linking the same library multiple times ever create a problem? For example, could the link fail with multiply-defined symbols if the same .o gets pulled in twice? Or is there any risk we could wind up with two copies of the same static object, creating subtle bugs?

基本上,我想知道是否有任何可能的链接 - 多次链接同一库的时间或运行时失败;如果是,如何触发它们。谢谢。

Basically, I want to know if there is any possibility of link-time or run-time failures from linking the same library multiple times; and if so, how to trigger them. Thanks.

推荐答案

我可以提供的只是缺乏反例。我实际上从来没有见过第一种形式(即使它显然更好),总是看到这解决了第二种形式,并没有观察到问题作为结果。

All I can offer is a lack of counter-example. I've actually never seen the first form before (even though it's clearly better) and always seen this solved with the second form, and haven't observed problems as a result.

即使这样,我仍然建议更改为第一种形式,因为它清楚地显示了库之间的关系,而不是依赖于链接器以特定的方式行为。

Even so I would still suggest changing to the first form because it clearly shows the relationship between the libraries rather than relying on the linker behaving in a particular way.

说,我建议至少考虑是否有可能重构代码将共同的部分拉进额外的库。

That said, I would suggest at least considering if there's a possibility of refactoring the code to pull out the common pieces into additional libraries.

这篇关于通过链接同一个库两次来解决循环依赖性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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