我们用nm看动态库时,会发现有些符号类型是"V",手册里解释如下:
说的是动态库中的weak symbol,缺省会被normal symbol替代,如果没有定义,则该symbol的值为0。
很抽象,是不是,我一直想找一个简单的例子。
最近看过一篇文章:
http://www.cs.virginia.edu/~wh5a/blog/2006/07/20/the-weak-attribute-of-gcc/
终于对所谓的weak symbol有了一点了解。
http://gcc.gnu.org/onlinedocs/gcc-4.1.1/gcc/Function-Attributes.html
讲了__attribute__的语法。
extern void foo() __attribute__((weak));
if (foo) foo();
}
程序居然能够编译通过,甚至成功执行!让我们来看看是为什么?
首先声明了一个符号foo(),属性为weak,但并不定义它,这样,链接器会将此未定义的weak symbol赋值为0,也就是说foo()并没有真正被调用,试试看,去掉if条件,肯定core dump!
extern void foo() ;
if (foo) foo();
}
这个是一般程序,编译过不了:
strong.c: undefined reference to `foo'
【foo.c】
void foo() {
printf("in foo./n");
}
OK!
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。
`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.
本文深入探讨了动态库中weak symbol的概念,解释了当weak定义符号与normal定义符号链接时,正常定义的符号将被使用;而当weak未定义符号链接且未定义时,其值将默认为0。并通过实例展示了weak symbol的实际应用。
1611

被折叠的 条评论
为什么被折叠?



