使用这个功能,你就可以在main函数执行之前,和main函数退出之后,执行你自己想要的操作。
示例:
#include <stdio.h>
#include <stdlib.h>
static void start (void) __attribute__ ((constructor));
static void stop (void) __attribute__ ((destructor));
int main (int argc, char* argv[])
{
printf ("%s is starting...\n", argv[0]);
printf ("start == %p\n", start);
printf ("stop == %p\n", stop);
printf ("%s is stopping...\n", argv[0]);
return 0;
}
void start (void)
{
printf ("Hello, world\n");
}
void stop (void)
{
printf ("Goodbye!\n");
}
运行结果:
Hello, world
../bin/constructor_destructor is starting...
start == 0x804845a
stop == 0x804846e
../bin/constructor_destructor is stopping...
Goodbye!
本文介绍如何在C++中使用构造函数和析构函数实现特定功能,通过实例展示了其在程序启动前和退出后的操作,包括初始化和清理工作。
2457

被折叠的 条评论
为什么被折叠?



