__attribute__中constructor和destructor[总结]

简介:

1、前言

  最近看到一份代码,看到一个函数前面用__attribute__((destructor))修饰,当时感觉有点怪怪的,搜了整个程序,也没发现哪个地方调用这个函数。于是从字面意思猜想,该函数会在程序结束后自动调用,与C++中的析构函数类似。第一次接触GNU下的attribute,总结一下。

2、__attribute__介绍

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

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

  若函数被设定为constructor属性,则该函数会在main()函数执行之前被自动的执行。类似的,若函数被设定为destructor属性,则该函数会在main()函数执行之后或者exit()被调用后被自动的执行。例如下面的程序:

复制代码
#include <stdio.h>
#include <stdlib.h>
static int * g_count = NULL;
__attribute__((constructor)) void load_file()
{
    printf("Constructor is called.\n");
    g_count = (int *)malloc(sizeof(int));
    if (g_count == NULL)
    {
    fprintf(stderr, "Failed to malloc memory.\n");
    }
}
__attribute__((destructor)) void unload_file()
{
    printf("destructor is called.\n");
    if (g_count)
    free(g_count);
}
int main()
{
    return 0;
}
复制代码

程序执行结果如下:

相关文章
|
2月前
|
缓存 前端开发 JavaScript
方法 constructor()
方法 constructor() 是 JavaScript 中构造函数的一个特殊方法,它用于创建和初始化对象。当使用 new 操作符创建一个对象时,构造函数的 constructor 方法会被自动调用。在 constructor 方法中,可以设置对象的属性和方法,以及执行一些初始化操作。
32 7
|
11月前
AttributeError: ‘set‘ object has no attribute ‘items‘
出现这个问题,原因可能是定义的header有问题
105 0
|
12月前
|
JavaScript 前端开发
constructor 属性
constructor 属性
55 0
|
JavaScript 前端开发
AttributeError: 'module' object has no attribute 'X509_up_ref'
AttributeError: 'module' object has no attribute 'X509_up_ref'
134 0
成功解决AttributeError: ‘JointGrid‘ object has no attribute ‘annotate‘
成功解决AttributeError: ‘JointGrid‘ object has no attribute ‘annotate‘
When will the reference ATTRIBUTE_REF of an BOL entity be cleared
When will the reference ATTRIBUTE_REF of an BOL entity be cleared
When will the reference ATTRIBUTE_REF of an BOL entity be cleared
|
TensorFlow 算法框架/工具
has no attribute ‘swish‘
has no attribute ‘swish‘
135 0
成功解决AttributeError: 'NoneType' object has no attribute '__array_interface__'
成功解决AttributeError: 'NoneType' object has no attribute '__array_interface__'
成功解决AttributeError: 'NoneType' object has no attribute '__array_interface__'
成功解决AttributeError: 'MapDataset' object has no attribute 'group_by_window'
成功解决AttributeError: 'MapDataset' object has no attribute 'group_by_window'
成功解决AttributeError: 'MapDataset' object has no attribute 'group_by_window'