在main 的前后呼出函数

3384阅读 3评论2011-01-28 shell_way
分类:C/C++

在开始之前请允许我声明我们在此所用的是GNU C,使用了GCC的扩张功能,所以请不要在VC 等编译器编译失败时对它发脾气。。。
好吧上代码:
  1. /*
  2.  * 文件名:before_and_after_main.c
  3.  * 注意:使用GCC系列编译器进行编译
  4.  */

  5. #include <stdio.h>

  6. __attribute__((constructor))
  7. void   before (void);

  8. __attribute__((destructor))
  9. void   after (void);

  10. int    main
  11. (void) {
  12.         
  13.        puts ("In main\n");

  14.        return 0;
  15. }

  16. __attribute__((constructor))
  17. void   before
  18. (void) {
  19.         
  20.        puts ("Before main\n");

  21.        return;
  22. }

  23. __attribute__((destructor))
  24. void   after
  25. (void) {
  26.                 
  27.        puts ("After main\n");

  28.        return;
  29. }
来个效果:
speller@SHELL-LAB:~/code/c$ gcc -o before_and_after_main before_and_after_main.c
speller@SHELL-LAB:~/code/c$ ./before_and_after_main
Before main

In main

After main

speller@SHELL-LAB:~/code/c$

上一篇:Vim配置文件 v2010-01
下一篇:程序的自动改写

文章评论