StdAfx + Header file - Order of inclusion in MFC application

≯℡__Kan透↙ 提交于 2019-11-26 11:39:43

问题


I am using Visual Studio 2005. I created an MFC based console application named \"StdAfx dependancy\". The IDE created the following files for me.

  1. Resource.h
  2. StdAfx Dependancy.h
  3. stdafx.h
  4. StdAfx Dependancy.cpp
  5. stdafx.cpp

I added another class CHelper with Helper.h and Helper.cpp as below.

Helper.h:

#pragma once

class CHelper
{
public:
    CHelper(void);
    ~CHelper(void);
};

Helper.cpp

#include \"StdAfx.h\"
#include \"Helper.h\"

CHelper::CHelper(void)
{
}

CHelper::~CHelper(void)
{
}

I created an object for CHelper in the main function; to achieve this I added Header.h file in the first line of StdAfx Dependancy.cpp as below; and I got the following errors.

d:\\codes\\stdafx dependancy\\stdafx dependancy\\stdafx dependancy.cpp(33) : error C2065: \'CHelper\' : undeclared identifier
d:\\codes\\stdafx dependancy\\stdafx dependancy\\stdafx dependancy.cpp(33) : error C2146: syntax error : missing \';\' before identifier \'myHelper\'
d:\\codes\\stdafx dependancy\\stdafx dependancy\\stdafx dependancy.cpp(33) : error C2065: \'myHelper\' : undeclared identifier

But when I include it after stdafx.h, the error vanishes. Why?

// Stdafx dependancy.cpp : Defines the entry point for the console application.
//

#include \"Helper.h\"

#include \"stdafx.h\"
#include \"Stdafx dependancy.h\"

// #include \"Helper.h\" --> If I include it here, there is no compilation error

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// The one and only application object

CWinApp theApp;

using namespace std;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    int nRetCode = 0;

    // initialize MFC and print and error on failure
    if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
    {
        // TODO: change error code to suit your needs
        _tprintf(_T(\"Fatal Error: MFC initialization failed\\n\"));
        nRetCode = 1;
    }
    else
    {
        CHelper myHelper;
    }

    return nRetCode;
}

回答1:


This link must give you some clue. Purpose of stdafx.h

The lines defined before the #include "stdafx.h" are ignored by the compiler. So if you want to actually include those files then you need to include them after the #include "stdafx.h".

Hope it is clear.




回答2:


In addition to ckv's answer, it makes little sense to include header files before "stdafx.h" as any non-trivial header file will contain framework types that are included there (e.g. any MFC types).



来源:https://stackoverflow.com/questions/3090473/stdafx-header-file-order-of-inclusion-in-mfc-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!