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 
相关推荐
吾与谁归in1 分钟前
C#脚本工具,支持智能提示自动补全(WPF + Roslyn + AvalonEdit)
开发语言·c#·wpf
码匠许师傅11 分钟前
【C++三方组件】OpenCV:计算机视觉的事实标准
c++
昂好的day13 分钟前
WPF 从零入门(上):WPF 是什么、XAML 语法、布局与样式全解
开发语言·c#·wpf
飞浪纪元[FWC–FE]15 分钟前
Qt 构建排错实录:从 MSB 1009 到生成器选型
开发语言·数据库·qt
fly-iot17 分钟前
【FDE知识库】(1):AI 编程时代开发语言选型分析,云使用go,企业用java,算法python,底层c
开发语言·人工智能·golang
云边有个稻草人17 分钟前
Prometheus Pushgateway教程:离线任务指标上报、Shell与Python示例、远程访问
开发语言·python·prometheus
暴走约伯19 分钟前
【VFX工具链源码拆解 01】总体架构:大型项目特效流程的程序化落地
开发语言·经验分享·3d·unity·架构·游戏引擎
C^h9 小时前
c++ string
开发语言·c++
raindayinrain10 小时前
c++高性能--原子操作,无锁编程,操作顺序
开发语言·c++·性能优化
学逆向的10 小时前
C++ 合并命名空间
开发语言·c++·网络安全