我们用nm看动态库时,会发现有些符号类型是"V",手册里解释如下:
"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.
说的是动态库中的weak symbol,缺省会被normal symbol替代,如果没有定义,则该symbol的值为0。
很抽象,是不是,我一直想找一个简单的例子。
最近看过一篇文章:
~wh5a/blog/2006/07/20/the-weak-attribute-of-gcc/终于对所谓的weak symbol有了一点了解。
讲了__attribute__的语法。
【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.
阅读(2199) | 评论(0) | 转发(1) |