amba start.S 分析 .weak作用

本文深入探讨了动态库中weak symbol的概念,解释了当weak定义符号与normal定义符号链接时,正常定义的符号将被使用;而当weak未定义符号链接且未定义时,其值将默认为0。并通过实例展示了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。
很抽象,是不是,我一直想找一个简单的例子。
             
最近看过一篇文章:
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__的语法。
 
【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.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值