2

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 ?

lucasg
  • 10,734
  • 4
  • 35
  • 57
  • 2
    Note that PCH stands on _Pre Compiled Header_, which helps compiler to reduce the compile time. – masoud Apr 16 '13 at 15:15
  • Precompiled headers can only be used when the same headers are being included as the very first. – sehe Apr 16 '13 at 15:18
  • @sehe : more like a duplication of this one (http://stackoverflow.com/questions/2976035/purpose-of-stdafx-h) – lucasg Apr 16 '13 at 15:35

3 Answers3

3

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

zakinster
  • 10,508
  • 1
  • 41
  • 52
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.

masoud
  • 55,379
  • 16
  • 141
  • 208
0

stdafx.h file includes common headers those are used along different files in a project. It's not a must to include it but then you have to manage all the headers along your project and this will cause to repeat some headers along different files.

gesus
  • 471
  • 1
  • 10
  • 24