Why stdfax.h should be the first include on MFC applications? [duplicate]
I want to know why this line exists on every MFC app (which force to make stdafx.h the first header included in every file) :
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
What are the reason(s) behind this behavior ?
Solution 1:
It's only true when using Precompiled Headers (PCH), and the reason why there shouldn't be anything before the #include "stdafx.h"
is :
Visual C++ will not compile anything before the #include "stdafx.h" in the source file, unless the compile option /Yu'stdafx.h' is unchecked (by default); it assumes all code in the source up to and including that line is already compiled
from http://en.wikipedia.org/wiki/Precompiled_header
Solution 2:
You should read this brief description stdafx.h
Compatible compilers (for example, Visual C++ 6.0 and newer) will precompile this file to reduce overall compile times. Visual C++ will not compile anything before the #include "stdafx.h" in the source file, unless the compile option /Yu'stdafx.h' is unchecked (by default); it assumes all code in the source up to and including that line is already compiled.
It implicitly says, to achieve advantages of PCH, you have to include stdafx.h
as soon as possible in inclusion hierarchy.