views:

64

answers:

2

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;
}

Thanks.

+3  A: 

This link must give you some clue. http://stackoverflow.com/questions/2976035/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.

ckv
You mean `#include "stdafx.h"`?
bdhar
yes sorry for the typo
ckv
+1  A: 

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).

Igor Zevaka