Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
987 views
in Technique[技术] by (71.8m points)

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

My problem can be summarised in the following:

bar.c:

#include <stdio.h>

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

main.c:

#include <stdio.h>

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...