0
votes

I have this extremely simple main function

#include "stdafx.h"
#include "abc.h"

int _tmain(int argc, _TCHAR* argv[])
{
    abc obj;
    obj.show();
    return 0;
}

Everything is compiling normally...but when i am writing

#include "abc.h" 
#include "stdafx.h"


    int _tmain(int argc, _TCHAR* argv[])
    {
        abc obj;
        obj.show();
        return 0;
    }

The compiler is going haywire..

error C2065: 'abc' : undeclared identifier

error C2146: syntax error : missing ';' before identifier 'obj'

error C2065: 'obj' : undeclared identifier

error C2228: left of '.show' must have class/struct/union

type is ''unknown-type''

Why is it mandatory to include

stdafx.h

at the start? I am new in C++ ...maybe I am making a silly mistake. Please help :(

(Using: VS2005 with C++ 98)

1
You should include stdafx.h directy in your abc.h if you requires declarations from it. At least, if the include order matters, it's a sign there is something wrong with the content of the .h files themselves.Bregalad
Its mandatory to include stdafx.h in every .cpp file but it has to be mentioned on the top of all the other .h includes......why is that?? thats my question... :(DeepN
@Bregalad No, no, no. stdafx.h is related to precompiled headers mechanism in VS. It has to be 1st ... because it has (it uses precompiler magic) =). It's not a dependency. One read, second read.luk32

1 Answers

3
votes

The issue that you're seeing is the fact that MS Visual C++ uses a feature called precompiled headers by default (other compilers on other platforms have a similar feature, I recall GCC for example having this feature). This ensures that all the code referenced up to the point of the precompiled header is pre-compiled, thus the compiler has less work to do at compilation time.

What happened when you switched that around was that it assumed that the contents of "abc.h" were already pre-compiled when they actually weren't. One easy solution would be to put #include "abc.h" inside stdafx.h. See here for a more details explanation of how the stdafx.h header works.

The precompiled headers option can be easily turned off in the compiler options. There should be a "precompiled headers/precompilation" category in the options, was in earlier Visual C++ IDE's I've encountered.