谁是最早执行的函数?main()? mainCRTStartUp

在main函数调用之前,还有一个函数需要得到执行,mainCRTStartup.此函数不在代码中,但是在链接器对我们程序进行链接的时候,会把mainCRTStartup编译到我们程序之中。main函数只是我们客户编写。
在CONSOLE(无Windows界面)程序中,main函数是用户定义的执行入口点,当程序编译成功后,连接器(linker)会将mainCRTStartup连接到exe中;exe执行时,一开始执行的是mainCRTStartup,而不是main。因为程序在执行时会调用时会调用各种各样的运行时库函数,因此程序执行之前必须要先初始化好运行时库,mainCRTStartup函数会负责相应的初始化工作,如果使用C++编程,还要执行全局类对象的构造函数。最后mainCRT才调用main函数
CONSOLE(无windows界面):mainCRTStartup(或wmainCRTStartup)=》main
w开头的函数是unicode版本的工程,CRTStartup:C Runtime startup Code
WINDOWS(有界面):WinMainCRTStartup(或wWinMainCRTStartUp)=》WinMain

如何在main()函数之前执行一些代码:
1.gcc中可以使用attribute关键字,声明constructor(main函数之前调用,构造函数)和destructorC(main函数之后调用,析构函数)函数,_attribute((constructor)) void before_main(){代码段}
2.VC中不支持attribute,可插入函数进入初始化函数表[_xi_a,_xi_z]c语言中和[_xc_a,_xc_z]c++语言中,由CRTInit调用,CRTInit由mainCRTStartUp调用。

# program data_seg(".CRT$XIU")   //XIU XIV XIW…在A和Z之间
		Static func *before1[]={before_main1函数};

3.C++:
法1:A a 全局对象初始化得到调用,构造函数在main之前得到调用
法2:Int g_iValue=func() 定义全局变量,使用函数的返回值为全局变量初始化,func也会在main函数之前得到运行。

用C++法二方法代码:

// cpp_premain.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;
using std::cout;

int func()
{
	cout<<"func() called before main()"<<endl;
	return 100;
}
class A
{
public:
	A()
	{
		cout<<"A() constructor called"<<endl;
	}
	~A()
	{
		cout<<"~A() destructor called"<<endl;
	}
};

A a;

int Value = func();

int _tmain(int argc, _TCHAR* argv[])
{
	cout<<"main() called"<<endl;
	return 0;
}

结果:

A() constructor called
func() called before main()
main() called
~A() destructor called
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值