Linking Order Matters When Linking Static Libraries in Your Program

17 Sep 2012

This is again some note to myself.

Today I tried to build the software I wrote at work, and kept getting linkage errors like this: undefined reference to sth. After analysing the problem, I knew immediately there are some dependencies among the libraries (statically linking) I linked together.

Then I noticed linking order matters! Since it is static linking, the dependent library has to be linked first. However, it took me a while to figure out you actually need to list the libaries in a reverse order of dependencies to the linker. That said, if library A depends on libray B, then the following should appear in your Makefile or build script:

g++ -lA -lB

Some Stackoverflow explanations for your information. Happy coding.