weak symbol
【weak.c】
extern void foo() __attribute__((weak));
int main() {
if (foo) foo();
}
程序居然能够编译通过,甚至成功执行!让我们来看看是为什么?
首先声明了一个符号foo(),属性为weak,但并不定义它,这样,链接器会将此未定义的weak symbol赋值为0,也就是说foo()并没有真正被调用,试试看,去掉if条件,肯定core dump!
【strong.c】
extern void foo() ;
int main() {
if (foo) foo();
}
这个是一般程序,编译过不了:
strong.c: undefined reference to `foo'
再添上一个定义文件:
【foo.c】
void foo() {
printf("in foo./n");
}
OK!
用nm检查一下:
linux:~/test/weak # nm weak.o
w foo
00000000 T main
linux:~/test/weak # nm foo.o
00000000 T foo
U printf
链接时,前面那个weak symbol会被后面这个代替,如果没有链接foo.o,也没问题,对应符号为0。
这就是weak symbol的意义。
-------------------------------------------------------------------------------------------------------------------------------------------
`V' The symbol is a weak object. When a weak defined symbol is linked with a normal defined symbol, the normal defined symbol is used with no error. When a weak undefined symbol is linked and the symbol is not defined, the value of the weak symbol becomes zero with no error.
`W' The symbol is a weak symbol that has not been specifically tagged as a weak object symbol. When a weak defined symbol is linked with a normal defined symbol, the normal defined symbol is used with no error. When a weak undefined symbol is linked and the symbol is not defined, the value of the weak symbol becomes zero with no error.