Understanding Precompiled Headers

When AppWizard generates a project, it generates switch settings and files for precompiled headers. You must understand how the make system processes precompiled headers in order to manage your projects effectively.

Visual C++ has two precompiled header "systems:" automatic and manual. Automatic precompiled headers, activated with the /Yx compiler switch, store compiler output in a "database" file. Manual precompiled headers are activated by the /Yc and /Yu switch settings and are central to all AppWizard-generated projects.

Precompiled headers represent compiler "snapshots" taken at a particular line of source code. In MFC library programs, the snapshot is generally taken immediately after the following statement:

#include  "StdAfx.h"

The file StdAfx.h contains #include statements for the MFC library header files. The file's contents depend on the options that you select when you run AppWizard, but the file always contains these statements:

#include <afxwin.h>
#include <afxext.h>

If you're using compound documents, StdAfx.h also contains the statement

#include <afxole.h>

and if you're using Automation or ActiveX Controls, it contains

#include <afxdisp.h>

If you're using Internet Explorer 4 Common Controls, StdAfx.h contains the statement

#include <afxdtctl.h>

Occasionally you will need other header files—for example, the header for template-based collection classes that is accessed by the statement

#include <afxtempl.h>

The source file StdAfx.cpp contains only the statement

#include  "StdAfx.h"

and is used to generate the precompiled header file in the project directory. The MFC library headers included by StdAfx.h never change, but they do take a long time to compile. The compiler switch /Yc, used only with StdAfx.cpp, causes creation of the precompiled header (PCH) file. The switch /Yu, used with all the other source code files, causes use of an existing PCH file. The switch /Fp specifies the PCH filename that would otherwise default to the project name (with the PCH extension) in the target's output files subdirectory. Figure 3-1 illustrates the whole process.

AppWizard sets the /Yc and /Yu switches for you, but you can make changes if you need to. It's possible to define compiler switch settings for individual source files. On the C/C++ tab in the Project Settings dialog box, if you select only StdAfx.cpp, you'll see the /Yc setting. This overrides the /Yu setting that is defined for the target.

Be aware that PCH files are big—5 MB is typical. If you're not careful, you'll fill up your hard disk. You can keep things under control by periodically cleaning out your projects' Debug directories, or you can use the /Fp compiler option to reroute PCH files to a common directory.

Figure 3-1. The Visual C++ precompiled header process.