C语言的__attribute__机制

1.理论介绍

__attribute__声明函数属性
可以使用__attribute__来声明函数的属性,这些属性可以帮助编译器优化调用或更仔细地检查代码的正确性。例如,属性(noreturn)用来指定函数从不返回。函数属性声明由__attribute__关键字引入,函数后跟一个用双括号括起来的属性说明。你可以在声明中指定多个属性,方法是在双括号里面用逗号将各个声明分开。

2 构造函数

以下是使用C语言的attribute构造函数的例子:

#include <stdio.h>
// A function with the attribute constructor
void function_with_attribute_constructor() __attribute__((constructor));
// The function to be called at the start of main()
void function_with_attribute_constructor()
{
    printf("This function is called automatically before main()\n");
}
// main() function
int main()
{
    printf("main() function.\n");
    return 0;
}

执行结果

This function is called automatically before main()
main() function.

可以看到,构造函数是在main函数之前执行的。

3 析构函数

以下是使用c语言实现的析构函数

#include <stdio.h>
 
void __attribute__((destructor)) my_fini(void)
{
    printf("Goodbye!\n");
}
int main(void)
{
    printf("Hello!\n");
    return 0;
}

执行结果

Hello!
Goodbye!
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值