Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

c++ - StdAfx + Header file - Order of inclusion in MFC application

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:codesstdafx dependancystdafx dependancystdafx dependancy.cpp(33) : error C2065: 'CHelper' : undeclared identifier
d:codesstdafx dependancystdafx dependancystdafx dependancy.cpp(33) : error C2146: syntax error : missing ';' before identifier 'myHelper'
d:codesstdafx dependancystdafx dependancystdafx 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
"));
        nRetCode = 1;
    }
    else
    {
        CHelper myHelper;
    }

    return nRetCode;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...