A weak symbol is symbol definition in object file or dynamic lib, which can be overridden by strong symbol.
A unix/linux linker uses the rule below to resolve symbols with the identical symbol name.
1. It doesn't allow two strong symbol have the same name
2. If there are one strong symbol and more than one weak symbol, it uses the strong symbol
3. If no strong symbol exists, and there is only one weak symbol, it uses the weak symbol
4. If no strong symbol exists, and there are several weak symbols, it uses one of them randomly
Here are a piece of code to demonstrate the usage of weak symbol.
[tli]$ more f2.c
#include<stdio.h>
void fun_()
{
printf("%s\n", __FUNCTION__);
}
extern void fun() __attribute__((weak, alias("fun_"))); //define a weak symbol fun, and it is a alias of function fun_
[tli]$ more main.c
#include<stdio.h>
extern void fun();
int main()
{
fun();
return 0;
}
[tli]$ gcc main.c f2.c
[tli]$ ./a.out
fun_
[tli]$ nm a.out | grep fun
00000000004004c0 W fun //weak symbol
00000000004004c0 T fun_ //strong symbol