写个函数在main函数执行前先运行
- way1:定义全局变量,变量类型为类对象,重写一下构造函数。
- way2.:全局变量(可以是普通全局或static全局)的初始化在程序初始阶段,先于main函数的执行。
- way3: 使用
__attribute((constructor))
设置函数构造(constructor)属性,对应的有destructor属性。
way1 与 way2 其实是一样的,实质都是全局变量,只是类对象是构造函数进行初始化,普通的全局变量通过调用一个函数来初始化。
关于static
- static全局在本cpp文件中使用,不能被其他文件使用;
- static局部在所在作用域内使用
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;
}