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 
相关推荐
倒头就睡的小比特3 天前
算法竞赛C++常用的STL
c++·算法
weilx12343 天前
C++笔记-文件IO-<fcntl.h>
c++
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
Smileyqp沛沛3 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
C语言小火车3 天前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光3 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
吞下星星的少年·-·3 天前
C++ 萌新语法入门篇
c++·算法比赛
霍霍的袁3 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
another heaven3 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法