首先寻找程序的入口函数WinMain ,WinMain 函数在 APPMODUL.cpp 中,就是下面的_tWinMain,这是一个宏定义。
_tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow)
{
// call shared/exported WinMain
return AfxWinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
}
但在这里程序运行后,不是直接进入_tWinMain函数内,而是进入CTestApp类中的结构体CTestApp(),这是因为有一个全局对象 theApp。
CTestApp::CTestApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only CTestApp object
CTestApp theApp;
// CTestApp initialization
这里要注意的是:
1.对于一个全局对象或一个全局变量,他们是在入口函数执行之前分配内存空间。作为全局对象来说就要调用构造函数为其分配内存空间。
2.theApp是一个序程对象(全局对象)
3.每一个MFC中有且仅有一个从CWinApp所派生出来的类(即CTestApp)。也只能有一个从应用程序类 所实例化的对象(即theApp),基类(父类)CWinApp是微软提供的,由此将两者联系起来了。
接下来程序才正式进去WinMain函数,也就是_tWinMain函数,我们注意到入口函数是通过AfxWinMain来表达的。下面介绍一下AfxWinMain。
以Afx-(application framework)为前缀的函数是 应用程序框架类函数。把类与类之间做了有机的集成,也都是全局函数,所以在每个类中都可以调用。AfxWinMain函数 在 WinMain.cpp 文件中。
int AFXAPI AfxWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow)
{
ASSERT(hPrevInstance == NULL);
int nReturnCode = -1;
CWinThread* pThread = AfxGetThread();
CWinApp* pApp = AfxGetApp();
// AFX internal initialization
if (!AfxWinInit(hInstance, hPrevInstance, lpCmdLine, nCmdShow))
goto InitFailure;
// App global initializations (rare)
if (pApp != NULL && !pApp->InitApplication())
goto InitFailure;
// Perform specific initializations
if (!pThread->InitInstance())
{
if (pThread->m_pMainWnd != NULL)
{
TRACE0("Warning: Destroying non-NULL m_pMainWnd\n");
pThread->m_pMainWnd->DestroyWindow();
}
nReturnCode = pThread->ExitInstance();
goto InitFailure;
}
nReturnCode = pThread->Run();
InitFailure:
#ifdef _DEBUG
// Check for missing AfxLockTempMap calls
if (AfxGetModuleThreadState()->m_nTempMapLock != 0)
{
TRACE1("Warning: Temp map lock count non-zero (%ld).\n",
AfxGetModuleThreadState()->m_nTempMapLock);
}
AfxLockTempMaps();
AfxUnlockTempMaps(-1);
#endif
AfxWinTerm();
return nReturnCode;
}