1、在C++中通过类的构造函数实现,这样一来,其实也可以实现在main函数之后打印信息:
#include <iostream> using namespace std; class a { public: a() { cout << "before the main function" << endl; } ~a(){ cout << "after the main function" << endl; }; }; a b; int main() { cout << "now main function is working" << endl; return 0; }
#include <stdio.h> void before_main()__attribute__((constructor)); void before_main() { printf("before the main function\n"); } void after_main()__attribute__((destructor)); void after_main() { printf("after the main function\n"); } int main() { printf("Now main function is working\n"); return 0; }
3、通过宏定义main函数实现
#include <stdio.h> void print() { #define main main() {printf("Hello World!\n");return 0;}int empty } int main() { return 0; }
#include<stdio.h> #include<stdlib.h> // // 声明将在 main 函数结束后执行的函数. // 这样的函数前置声明很特别吧!我以前也没想到过. // void fn1(void), fn2(void), fn3(void), fn4(void); int main(void) { // // 注册需要在 main 函数结束后执行的函数. // 请注意它们的注册顺序和执行顺序,看看它们的输出结果多有趣! // atexit(fn1); atexit(fn2); atexit(fn3); atexit(fn4); // 这条输出语句具有参照性,它可不是最后一句输出. puts("This is executed first."); // // EXIT_SUCCESS 代表 0,它定义在 stdlib.h 中. // 我只是顺便提一下,也许你知道,但我担心你不知道,呵呵. // return EXIT_SUCCESS; } void fn1(void) { printf("next.\n"); } void fn2(void) { printf("executed "); } void fn3(void) { printf("is "); } void fn4(void) { printf("This "); }
#include <stdio.h> struct a { a() { printf("before the main function\n"); } ~a() { printf("after the main function\n"); } }; a b; int main() { printf("Now main function is working\n"); return 0; }
原文:http://blog.csdn.net/u012925008/article/details/44586845