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 
相关推荐
Titan202411 小时前
Linux动静态库
linux·服务器·c++
辣椒思密达11 小时前
Python公开数据采集实战:如何解决请求高频拦截与Session会话中断问题
开发语言·python
j_xxx404_11 小时前
MySQL表操作硬核解析:从 CREATE TABLE 到磁盘文件、ALTER TABLE 与 DDL 风险
运维·服务器·数据库·c++·mysql·adb·ai
Albart57512 小时前
Python 实战教程:用 30 分钟学会解决真实问题
开发语言·python
2301_7736436212 小时前
ceph池
开发语言·ceph·python
两年半的个人练习生^_^12 小时前
JMM 进阶:彻底理解 CAS 实现原理
java·开发语言
wuminyu12 小时前
Java锁机制之park和unpark源码剖析
java·linux·c语言·jvm·c++
半个烧饼不加肉12 小时前
JS 底层探究-- 事件循环
开发语言·前端·javascript
asdfg125896312 小时前
C 语言中产生伪随机数的标准做法
c语言·开发语言
玖玥拾12 小时前
C/C++ 基础笔记(十一)类的进阶
c语言·c++·设计模式·