How to make gcc link strong symbol in static library to overwrite weak symbol?

I am puzzled by the answer given by max.haredoom (and that it was accepted). The answer deals with shared libraries and dynamic linking, whereas the question was clearly about the behavior of static linking using static libraries. I believe this is misleading.

When linking static libraries, ld does not care about weak/strong symbols by default: it simply resolves an undefined symbol to a first-encountered symbol (so the order of static libraries in the command line is important).

However, this default behavior can be changed using the --whole-archive option. If you rewrite your last step in Makefile as follows:

gcc main.c -L. -Wl,--whole-archive -lbar -Wl,--no-whole-archive

Then you will see:

$ ./a.out
bar

In a nutshell, --whole-archive forces the linker to scan through all its symbols (including those already resolved). If there is a strong symbol that was already resolved by a weak symbol (as in our case), the strong symbol will overrule the weak one.

Also see a great post on static libraries and their linking process “Library order in static linking” by Eli Bendersky and this SO question.

Leave a Comment