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

user1777342 picture user1777342 · Oct 26, 2012 · Viewed 15.6k times · Source

My problem can be summarised in the following:

bar.c:

#include <stdio.h>

void bar() {
    printf("bar\n");
}

main.c:

#include <stdio.h>

void __attribute__((weak)) bar() {
    printf("foo\n");
}

int main() {
    bar();
    return 0;
}

Makefile:

all:
    gcc -c bar.c
    ar -rc libbar.a bar.o
    gcc main.c -L. -lbar

Output:

$ ./a.out
foo

So the weak symbol bar in main.c is not overwritten by the strong symbol in bar.c due to bar.c being linked to main.c in a static library libbar.a.

How can I tell gcc to make the strong symbol in libbar.a to overwritten the weak symbol in main.c?

Answer

Dmitrii Kuvaiskii picture Dmitrii Kuvaiskii · May 12, 2016

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.