ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

【转】linux gcc _attribute__((weak)) 简介及作用

2021-11-09 09:01:23  阅读:225  来源: 互联网

标签:__ gcc 调用 符号 attribute weak weakref 模块


最新在项目架构代码上看到了有使用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

标签:__,gcc,调用,符号,attribute,weak,weakref,模块
来源: https://www.cnblogs.com/sggggr/p/15527221.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有