如何在C语言中使用constructor和destructor,gcc环境
使用这个功能,你就可以在main函数执行之前,和main函数退出之后,执行你自己想要的操作。具体原理,网上很多,自己google一下就找到了,这里只是给一个例子。
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 static void start(void) __attribute__ ((constructor));
5 static void stop(void) __attribute__ ((destructor));
6
7 int
8 main(int argc, char *argv[])
9 {
10 printf("start == %p\n", start);
11 printf("stop == %p\n", stop);
12
13 exit(EXIT_SUCCESS);
14 }
15
16 void
17 start(void)
18 {
19 printf("hello world!\n");
20 }
21
22 void
23 stop(void)
24 {
25 printf("goodbye world!\n");
26 }
27
2 #include <stdlib.h>
3
4 static void start(void) __attribute__ ((constructor));
5 static void stop(void) __attribute__ ((destructor));
6
7 int
8 main(int argc, char *argv[])
9 {
10 printf("start == %p\n", start);
11 printf("stop == %p\n", stop);
12
13 exit(EXIT_SUCCESS);
14 }
15
16 void
17 start(void)
18 {
19 printf("hello world!\n");
20 }
21
22 void
23 stop(void)
24 {
25 printf("goodbye world!\n");
26 }
27
运行结果:
hello world!
start == 0x4005fb
stop == 0x40060b
goodbye world!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步