方法一:
全局變量的構造函數,會在main之前執行。
#include <iostream> using namespace std; class app { public: //構造函數 app() { cout<<"First"<<endl; } }; app a; // 申明一個全局變量 int main() { cout<<"Second"<<endl; return 0; }
方法二:
全局變量的賦值函數,會在main之前執行。(C中好像不允許通過函數給全局變量賦值)
#include <iostream> using namespace std; int f(){ printf("before"); return 0; } int _ = f(); int main(){ return 0; }
方法三:
如果是GNUC的編譯器(gcc,clang),就在你要執行的方法前加上 __attribute__((constructor))
#include<stdio.h> __attribute__((constructor)) void func() { printf("hello world\n"); } int main() { printf("main\n"); //從運行結果來看,並沒有執行main函數 }
同理,如果想要在main函數結束之后運行,可加上__sttribute__((destructor)).
#include<stdio.h> void func() { printf("hello world\n"); //exit(0); return 0; } __attribute((constructor))void before() { printf("before\n"); func(); } __attribute((destructor))void after() { printf("after\n"); } int main() { printf("main\n"); //從運行結果來看,並沒有執行main函數 }
參考鏈接:
1. CSDN_darmao-不執行main函數可以執行一段程序嗎?