0

This seems to be a question from a ancient time.

Imagine, we have a executable named juggle who has the following dependency:

juggle → libfoo.a → libbar.a

Then, we must write link command like this:

g++ -o juggle juggle.cpp -lfoo -lbar

but NOT:

g++ -o juggle juggle.cpp -lbar -lfoo

This problem exists as well when linking a .so (libpickle.so for example) . If you write lib list improperly, bar's code will not get into pickle but the link succeeds. Only when you try to dynamic load libpickle.so will you realize you have missed bar.

That is an over simplified example. In real world I constantly face so many libraries(many from our own team) to link and remembering lib dependency order can be a burden. I say "burden" because there is some other compiler(Visual C++) who don't put this burden on us.

So, I think it is best practice to always write linker component twice,

g++ -o juggle juggle.cpp -lfoo -lbar -lfoo -lbar

and, this also works when circular dependency exists.

Does anyone have the same idea with me, or, a better solution?

EDIT: I finally realize merely writing linker component twice does not necessarily make linking success. Assume a dependency of A -> B -> C , and we list library in order of C B A, we have to write C B A three times.

Jimm Chen
  • 3,411
  • 3
  • 35
  • 59

2 Answers2

3

Another option is to use the linker --start-group and --end-group options to specify a group of libraries that have circular dependencies.

See this SO answer for more information.

Community
  • 1
  • 1
brady
  • 2,227
  • 16
  • 18
  • Do you mean, we can actually wrap every -lxxx inside ``--start-group`` and ``--end-group``, without any side-effect , except sacrificing a bit linking time? – Jimm Chen May 07 '12 at 01:45
  • Correct. The linker will repeatedly search through the list of libraries contained within `--start-group` and `--end-group` until the number of unresolved references is no longer decreasing. – brady May 07 '12 at 01:55
2

Of the alternatives you have presented, the better idea is to write the -l options in the correct order such that the dependencies are resolved in order. Only in the case where you have a circular library dependency (which you should avoid) would you need to mention the same library twice in the -l options.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • Remembering lots of dependency is a burden. Don't you think so? – Jimm Chen May 07 '12 at 01:40
  • You don't have to remember the dependencies. When developing complex software, you should have a table or graph that shows the relationships between your static libraries. Then when you introduce a new library, it should be easy to see where it will fit. – Greg Hewgill May 07 '12 at 01:46
  • Thanks. But I think we would be better off not manually maintaining that(because management is a cost), unless we can find a way to automatically generate that table. – Jimm Chen May 07 '12 at 01:52