main函数执行前执行一个函数的写法
生活随笔
收集整理的這篇文章主要介紹了
main函数执行前执行一个函数的写法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
寫個函數(shù)在main函數(shù)執(zhí)行前先運行
- way1:定義全局變量,變量類型為類對象,重寫一下構(gòu)造函數(shù)。
- way2.:全局變量(可以是普通全局或static全局)的初始化在程序初始階段,先于main函數(shù)的執(zhí)行。
- way3: 使用__attribute((constructor))設置函數(shù)構(gòu)造(constructor)屬性,對應的有destructor屬性。
way1 與 way2 其實是一樣的,實質(zhì)都是全局變量,只是類對象是構(gòu)造函數(shù)進行初始化,普通的全局變量通過調(diào)用一個函數(shù)來初始化。
關于static
- static全局在本cpp文件中使用,不能被其他文件使用;
- static局部在所在作用域內(nèi)使用
code example
#include <iostream>using namespace std;//way1 class BeforeMain {public:BeforeMain(); }; BeforeMain::BeforeMain() {cout<<"before main"<<endl; }BeforeMain bfm;//way2 int before_main() {cout<<"this is a global function"<<endl;return 0; } int i = before_main();//way3__attribute((constructor))void before() {cout<<"constructor: before main"<<endl; }int main() {cout << "Hello world!" << endl;return 0; } 與50位技術專家面對面20年技術見證,附贈技術全景圖總結(jié)
以上是生活随笔為你收集整理的main函数执行前执行一个函数的写法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

- 上一篇: C++实现虚拟内存页面置换算法(FIFO
- 下一篇: 跨站请求伪造攻击(CSRF)