Greeting, I'm novice in MFC area.
I have a question about process of starting MFC application.
I learned that unlike SDK program, I don't have to write WinMain. Because It is supplied by the class library and is called when the application starts up.* (See reference here : https://msdn.microsoft.com/en-us/library/akdx0603.aspx)
And my curious part is here: *Then CWinApp calls member functions of the application object to initialize and run the application.
That sentence indicates that CWinApp already know address value of application object which is made by a programmer.
However, even though application object is defined as global variable, how can WinMain function find application object's address value?
I couldn't find any connection or declaration in my sample MFC code which brings address value to the WinMain function.
#include <afxwin.h>
class CHelloApp : public CWinApp
{
public:
virtual BOOL InitInstance();
};
class CMainFrame : public CFrameWnd
{
public:
CMainFrame();
protected:
afx_msg void OnPaint();
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
DECLARE_MESSAGE_MAP()
};
CHelloApp theApp;
BOOL CHelloApp::InitInstance()
{
m_pMainWnd = new CMainFrame;
m_pMainWnd->ShowWindow(m_nCmdShow);
return TRUE;
}
CMainFrame::CMainFrame()
{
Create(NULL, "HelloMFC Application");
}
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_WM_PAINT()
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()
Good question, but you could answer it yourself when running your exe under a debugger, setting breakpoints at the right places and stepping into MFC source code.
The CRT provides a function mainCRTStartup. This function is the entry point that gets called when your program starts. mainCRTStartup calls __tmainCRTStartup. This function first calls _initterm to call the constructors for all global objects - like your CWinApp theApp. That constructor also calls CWinApp::CWinApp which stores the this pointer in a global state variable. When that is done __tmainCRTStartup calls WinMain which calls AfxWinMain. AfxWinMain is reading out the pointer to CWinApp theApp from the global state variable and calls the CWinApp's virtual member functions.
This only works because...
this pointerCWinApp object existsCWinApp is used as an interface and thus the MFC does not need to know how exactly your CWinApp derived class looks likeIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With