欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

编译 / __attribute__(constructor)和__attribute__(destructor)

发布时间:2024/10/14 编程问答 52 豆豆
生活随笔 收集整理的这篇文章主要介绍了 编译 / __attribute__(constructor)和__attribute__(destructor) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

一、前言

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

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

二、__attribute__ 介绍

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

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

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

如果函数被设定为 constructor 属性,则该函数会在 main() 函数执行之前被自动的执行;

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

三、验证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.

转载:__attribute__(constructor)和__attribute__(destructor)_sun172270102的博客-CSDN博客___attribute__(constructor)

(SAW:Game Over!)

总结

以上是生活随笔为你收集整理的编译 / __attribute__(constructor)和__attribute__(destructor)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。