zoukankan      html  css  js  c++  java
  • 【转】linux gcc _attribute__((weak)) 简介及作用

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

  • 相关阅读:
    条件变量:为什么要与互斥锁配套使用?为什么要使用while来避免虚假唤醒?
    【转】高性能IO之Reactor模式
    LeetCode127:单词接龙
    CF1245F: Daniel and Spring Cleaning
    权值线段树学习笔记
    luogu_4317: 花神的数论题
    luogu_2605: 基站选址
    入门平衡树: Treap
    CF1244C: The Football Season
    luogu_1156: 垃圾陷阱
  • 原文地址:https://www.cnblogs.com/sggggr/p/15527221.html
Copyright © 2011-2022 走看看