GNU C之__attribute__

__attribute__可以设置函数属性(Function Attribute)、变量属性(Variable Attribute)和类型属性(Type Attribute)

__attribute__前后都有两个下划线,并且后面会紧跟一对原括弧,括弧里面是相应的__attribute__参数

1. 变量别名:

语法:type newname __attribute__((alias("oldname")));

#include <stdio.h>
int oldname = 1;
extern int newname __attribute__((alias("oldname"))); // declaration
void foo(void)
{
    printf("newname = %d\n", newname); // prints 1
}

2. 弱符号:

若两个或两个以上全局符号(函数或变量名)名字一样,而其中之一声明为weak属性,则这些全局符号不会引发重定义错误。链接器会忽略弱符号,去使用普通的全局符号来解析所有对这些符号的引用,但当普通的全局符号不可用时,链接器会使用弱符号。当有函数或变量名可能被用户覆盖时,该函数或变量名可以声明为一个弱符号。

//模块A中调用func,但是不确定外部是否提供了该函数
...
extern int func(void);
 
...
 
int a = func();
 
...

如果直接这么调用,如果外部不提供该函数程序可能出现crash。

所以在本模块中__attribute__((weak))就派上了用场

int  __attribute__((weak))  func(......)
 
{
 
    return 0;
 
}

猜你喜欢

转载自www.cnblogs.com/guxuanqing/p/11184758.html
GNU