C++(和c語言中)如何在main()函數執行之前執行一個函數?

轉自:https://www.cnblogs.com/klcf0220/p/5663487.html

在C語言中,如果使用GCC的話,可以通過attribute關鍵字聲明constructor和destructor(C語言中如何在main函數開始前執行函數

#include <stdio.h>  
  
__attribute((constructor)) void before_main()  
{  
    printf("%s/n",__FUNCTION__);  
}  
  
__attribute((destructor)) void after_main()  
{  
    printf("%s/n",__FUNCTION__);  
}  
  
int main( int argc, char ** argv )  
{  
    printf("%s/n",__FUNCTION__);  
    return 0;  
}  

在C++中,利用全局變量和構造函數的特性,通過全局變量的構造函數執行(C++語言怎麼在main函數執行之前執行一段代碼

#include <Iostream>
using namespace std;

class TestClass
{
        public:
                TestClass();
};


TestClass::TestClass()
{
        cout<<"TestClass"<<endl;
}

TestClass Ts;//定義個全局變量,讓類裏面的代碼在main之前執行

int main()
{
        cout<<"main"<<endl;

        return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章