轉自: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;
}