attribute
__attribute__可以设置函数属性(Function Attribute)、变量属性(Variable Attribute)和类型属性(Type Attribute)
__attribute__语法格式为:attribute ((attribute-list))
Declaring Attributes of Functions(声明函数属性)
在 GNU C and C++中,可以使用function attributes帮助开发者把一些属性添加到函数声明中,这可帮助编译器优化调用或更仔细地检查代码的正确性
1. alias attrbute:
alias属性使声明作为另一个symbol的别名发出,前提是symbol声明完全与声明完全一样(the same type, and for variables, also the same size and alignment),使用格式如下:
void __f () { /* Do something. */; }
void f () __attribute__ ((weak, alias ("__f"))); // 定义
以上代码为f函数声明的增加属性:指定f为__f的弱别名。调用f时实际就是调__f函数
代码验证:
# include <stdio.h>
#define __stringify_1(x...) #x // #的作用是将宏参数字符串化,如:#do = > "do"
#define __stringify(x...) __stringify_1(x)
void sys_socket(int n) __attribute__((alias(__stringify(SyS_socket))));
void SyS_socket(int num) {
printf("%d,%s\n", num, "you call SYS_socket");
}
int main(void) {
sys_socket(1); // 调用sys_cocket就是第哦啊用Sys_socket函数
}
下为执行后输出:
╭─cs at css in ~/C_test using
╰─ ./a.out
1,you call SYS_socket
本文介绍了GCC和C++中使用__attribute__关键字为函数添加属性的功能,例如通过alias属性创建函数别名。通过示例展示了如何使用__attribute__((weak, alias))创建弱别名,使得调用函数f时实际上调用了__f函数,并通过代码验证了其实现。该特性有助于编译器优化和代码正确性检查。
148

被折叠的 条评论
为什么被折叠?



