DeepN
DeepN

Reputation: 344

Why mandatory to include stdafx.h at the start?

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)

Upvotes: 0

Views: 694

Answers (1)

display101
display101

Reputation: 2085

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.

Upvotes: 3

Related Questions