最新在项目架构代码上看到了有使用weak,以前没有看到过,所以写一篇文章记录。
场景:
A、B两个模块,A模块调用了不确定B模块是否提供了函数,但是又不得不调用,这个时候在A模块中再申明一个弱符号函数,
即用weak。如果外部提供了调用外部的,如果没有提供调用申明的。
弱符号
若两个或两个以上全局符号(函数或变量名)名字一样,而其中之一声明为weak属性,则这些全局符号不会引发重定义错误。链接器会忽略弱符号,去使用普通的全局符号来解析所有对这些符号的引用,但当普通的全局符号不可用时,链接器会使用弱符号。当有函数或变量名可能被用户覆盖时,该函数或变量名可以声明为一个弱符号。
示例:
//模块A中调用func,但是不确定外部是否提供了该函数
...
extern int func(void);
...
int a = func();
...
如果直接这么调用,如果外部不提供该函数程序可能出现crash。
所以在本模块中__attribute__((weak))就派上了用场
int __attribute__((weak)) func(......)
{
return 0;
}
这样的话如果模块B提供了func就调用模块B的,如果没提供就调用本模块在中weak声明的
最后附上gcc官方文档:
在GCC的官方文档中,对weak和weakref的描述如下:
http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html#Function-Attributes
weak
The weak attribute causes the declaration to be emitted as a weak symbol rather than a global. This is primarily useful in defining library functions which can be overridden in user code, though it can also be used with non-function declarations. Weak symbols are supported for ELF targets, and also for a.out targets when using the GNU assembler and linker.
weakref
weakref (“target”)
The weakref attribute marks a declaration as a weak reference.
Without arguments, it should be accompanied by an alias attribute naming the target symbol. Optionally, the target may be given as an argument to weakref itself. In either case, weakref implicitly marks the declaration as weak. Without a target, given as an argument to weakref or to alias, weakref is equivalent to weak.
作者:侵蚀昨天
来源:CSDN
原文:https://blog.csdn.net/q2519008/article/details/82774774