gcc中函数或者变量的weak属性

本文介绍了GCC编译器中弱符号(weak symbol)的概念及其使用场景,通过示例展示了如何利用弱符号属性来避免链接时的冲突,并解释了弱别名(weak alias)与弱符号类似的作用。
gcc reference里提到:

A function with this attribute has its name emitted as a weak
symbol instead of a global name. This is primarily for the naming
of library routines that can be overridden by user code.

weak symbol
Having two or more global symbols of the same name will not cause a conflict as long as all but one of them are declared as being weak symbols. The linker ignores the definitions of the weak symbols and uses the normal global symbol definition to resolve all references, but the weak symbols will be used if the normal global symbol is not available. A weak symbol can be used to name functions and data that can be overridden by user code. A weak symbol is also referred to as a weak alias, or simply weak.


通过简单的例子可以看出,weak属性可以让编译器在编译的时候忽略函数未定义的错误。

$cat weak.c
extern void foo() __attribute__((weak));
int main() {
if (foo) foo();
}
$ gcc weak.c -o weak
$ ./weak
$


weak alias 具有和weak symbol类似的作用。
int __centon() { return(100); }

void centon() __attribute__((weak,alias(“__centon”)));

原文链接:http://blog.chinaunix.net/uid-20593827-id-1918496.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值