Resolving circular dependencies by linking the same library twice?

Nemo picture Nemo · Feb 21, 2012 · Viewed 16.1k times · Source

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.

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

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

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

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

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.

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.

Answer

Mark B picture Mark B · Feb 21, 2012

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.