attribute((constructor)) 在C/C++中的应用

参考:https://www.jianshu.com/p/dd425b9dc9db

attribute介绍:

在C/C++编程中,attribute((constructor)) 是一个GCC编译器特有的属性,用于指定函数在 main() 函数执行之前自动执行,而 attribute((destructor)) 则指定函数在 main() 函数执行之后或 exit() 被调用后执行。这些函数通常用于初始化和清理程序中隐式使用的数据。

作用总结:

constructor参数: 让系统执行main()函数之前调用函数(被__attribute__((constructor))修饰的函数).同理, destructor让系统在main()函数退出或者调用了exit()之后,调用我们的函数.带有这些修饰属性的函数,对于我们初始化一些在程序中使用的数据非常有用.

示例代码:

以下是一个简单的示例,展示了如何使用 attribute((constructor))attribute((destructor)) 属性:

复制代码
#include <stdio.h>
#include <stdlib.h>
static void before_main(void) __attribute__((constructor));
static void after_main(void) __attribute__((destructor));
static void before_main() {
   printf("before main\n");
}
static void after_main(void) {
   printf("after main\n");
}
int main() {
   printf("main\n");
   return 0;
}

运行效果:

复制代码
before main 
main
after main 
相关推荐
大不点wow24 分钟前
Java序列化与反序列化:让对象走出JVM
java·开发语言·jvm
阿里嘎多学长24 分钟前
2026-07-22 GitHub 热点项目精选
开发语言·程序员·github·代码托管
小保CPP26 分钟前
OpenCV C++将多张图像合并为webp动图
c++·人工智能·opencv·计算机视觉
噢,我明白了28 分钟前
Java中日期和字符串的处理
java·开发语言·日期
爱刷碗的苏泓舒29 分钟前
C 语言 if-else 与 switch-case 分支语句对比
c语言·开发语言
-银雾鸢尾-38 分钟前
C#中的泛型约束
开发语言·c#
雪碧透心凉_1 小时前
while 循环与循环嵌套
开发语言·python
乐观勇敢坚强的老彭1 小时前
信奥C++一维数组笔记
开发语言·c++·笔记
码上有光1 小时前
异常和智能指针
java·大数据·c++·servlet·异常·智能指针
这就是佬们吗1 小时前
Python入门⑤-异常处理、文件操作与实战项目
开发语言·数据库·python·算法·pycharm