如何在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 

运行结果:

hello world!

start == 0x4005fb

stop == 0x40060b

goodbye world!

原文地址:https://www.cnblogs.com/Hacker/p/1750383.html