0

Static linking order is important for GCC, and it makes a lot of problems with static versions creation for a lot of widely used libraries, including libgd, libarchive, MySql Connector C, etc. Usually included configure script supposes that we use shared libraries, and even if we setup static build, it still ignores that fact and places static libraries in wrong order, so it consumes time to find the error and edit makefile manually.

From the other hand, competitor compilers can build static libraries in any order, for example, Microsoft Visual C++ doesn't have this problem, so it looks like must be a way to fix this issue.

Is there any way to force gcc to order static libraries automatically like Visual C++ does it?

Vitalii
  • 4,434
  • 4
  • 35
  • 77
  • This doesn't really answer your question of how to avoid editing the generated makefiles, but a trick I have used for simpler makefiles when I run into this is to just repeat the list of libraries 3 times when linking. So for instance if the linking phase looked like this: `gcc -o program $(LDFLAGS) $(LIBS)`, I can change it to `gcc -o program $(LDFLAGS) $(LIBS) $(LIBS) $(LIBS)` Then you don't have to worry about order as it will always find the symbol either forward or backward in the list of libs. It doesn't appear the make the executable any larger to do this. – John Morris Jan 22 '15 at 18:52
  • I tried to put the same library 2 times (for example, `-lz -lpng -lz`), but at least for `gcc 4.9.2` it doesn't help. – Vitalii Jan 22 '15 at 18:56
  • Ld has a flag to "order static libraries automatically like Visual C++ does", --start-group/--end-group, check the manual. Here is also a helpfull [resource](http://eli.thegreenplace.net/2013/07/09/library-order-in-static-linking) discussing ld intricacies in an entertaining way. – Nick Zavaritsky Jan 22 '15 at 19:30
  • @Vitaliy does it work with `-lz -lpng -lz -lpng -lz -lpng` ? When I used that trick it took 3x repeat to make it work. See the comment by @Nick_Zavaritsky it sounds like a better solution. – John Morris Jan 22 '15 at 19:56
  • I think [this](http://stackoverflow.com/questions/45135/linker-order-gcc) is what you're asking. Try: `-Wl,--start-group -Wl,--end-group` – Brett Hale Jan 22 '15 at 20:12
  • Hi, thanks for your advices. Idea with `-Wl` is very good, however, it works if you create makefile manually, because `configure` scripts included in many open source libraries reorder options. For example, when I build completely static `libgd` with static dependencies, it reorders options so libraries appear not inside `start-group` and `end-group` even if I put them inside group with `LDFLAGS`. – Vitalii Jan 23 '15 at 09:25

1 Answers1

2

Wrap the list of libraries with flags -Wl,--start-group and -Wl,--end-group during linking.

These flags ensures that all the unresolved symbols are looked up in all the mentioned libraries (independent of the order).