linux symbol,Linux 的weak symbol

我们用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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值