C语言:__attribute__(constructor)和__attribute__(destructor)

1、前言

最近看代码,看到一个函数前面用__attribute__((constructor))修饰,搜了整个程序,没发现哪个地方调用这个函数。如下:

__attribute__((constructor)) void load_file()
{
    printf("Constructor is called.\n");
    g_count = (int *)malloc(sizeof(int));
}

2、__attribute__介绍

__attribute__可以设置函数属性(Function Attribute)、变量属性(Variable Attribute)和类型属性(Type Attribute)。__attribute__前后都有两个下划线,并且后面会紧跟一对原括弧,括弧里面是相应的__attribute__参数。

__attribute__语法格式为:__attribute__ ( ( attribute-list ) )

如果函数被设定为constructor属性,则该函数会在main()函数执行之前被自动的执行;若函数被设定为destructor属性,则该函数会在main()函数执行之后或者exit()被调用后被自动的执行。

3、验证demo程序

例如下面的程序:

#include <stdio.h>
#include <stdlib.h>
static int * g_count = NULL;
__attribute__((constructor)) void load_file()
{
    printf("Constructor is called.\n");
}
__attribute__((destructor)) void unload_file()
{
    printf("destructor is called.\n");
}

int main()
{
    printf ("this is main function\n");
    return 0;
}

执行结果如下:

Constructor is called.
this is main function
destructor is called.
  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
__attribute__是一个编译属性,用于向编译器描述特殊的标识、错误检查或高级优化。它是GNU C的一个特性,可以用于设置函数属性、变量属性和类型属性等。在给函数、变量或类型添加属性时,可以使用__attribute__来指定属性列表。例如,可以使用__attribute__((constructor))来在main函数执行之前执行某个函数,使用__attribute__((destructor))来在main函数执行之后执行某个函数。\[1\]这些属性可以用于实现一些特殊的功能或行为,比如在程序运行前后执行一些初始化或清理操作。在给函数、变量或类型添加属性时,需要按照特定的格式来设置,比如使用__attribute__((attr_list))的形式来指定属性列表。\[2\]\[3\] #### 引用[.reference_title] - *1* *3* [C语言attribute机制](https://blog.csdn.net/weixin_37867857/article/details/102940773)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [C语言再学习 -- __attribute__详解](https://blog.csdn.net/qq_29350001/article/details/129390465)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值