Nic*_*ick 40 c c++ program-entry-point startup
可能重复:
main()是否真的启动了C++程序?
可以在程序启动前调用我的函数吗?我该怎么做这项工作C++还是C?
Luc*_*ore 45
您可以拥有全局变量或static类成员.
1)static班级成员
//BeforeMain.h
class BeforeMain
{
static bool foo;
};
//BeforeMain.cpp
#include "BeforeMain.h"
bool BeforeMain::foo = foo();
Run Code Online (Sandbox Code Playgroud)
2)全局变量
bool b = foo();
int main()
{
}
Run Code Online (Sandbox Code Playgroud)
请注意此链接 - http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.14/提议备选方案的镜像 - 由Lundin发布.
gli*_*ite 30
在C++有一个简单的方法:用一个全局对象的构造函数.
class StartUp
{
public:
StartUp()
{ foo(); }
};
StartUp startup; // A global instance
int main()
{
...
}
Run Code Online (Sandbox Code Playgroud)
这是因为全局对象是在main()开始之前构造的.正如Lundin指出的那样,要注意静态初始化命令fiasco.
Eig*_*ght 18
如果使用gcc和g++编译器,那么这可以通过使用来完成__attribute__((constructor))
例如::
在gcc(c)::
#include <stdio.h>
void beforeMain (void) __attribute__((constructor));
void beforeMain (void)
{
printf ("\nbefore main\n");
}
int main ()
{
printf ("\ninside main \n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在g ++(c ++)::
#include <iostream>
using namespace std;
void beforeMain (void) __attribute__((constructor));
void beforeMain (void)
{
cout<<"\nbefore main\n";
}
int main ()
{
cout<<"\ninside main \n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
CB *_*ley 14
在C++中,它是可能的,例如
static int dummy = (some_function(), 0);
int main() {}
Run Code Online (Sandbox Code Playgroud)
在C中,这是不允许的,因为具有静态存储持续时间的对象的初始化器必须是常量表达式.