Two Choices for Precompiling Code
With Visual C++, you can precompile any C or C++ code; you are not limited to precompiling only header files. To precompile headers, choose from the following approaches:
- Automatic precompiling
- Manual precompiling
The first approach is quick and easy. The second approach requires some planning, but it offers significantly faster compilations if you precompile source code other than simple header files.
Use automatic precompiling if you want the compiler to decide when to create and use precompiled headers.
The automatic precompiled-header option is (/YX). The /YX option causes the compiler to either create a precompiled header with a default name of VCxy.pch, where xy are the major and minor versions of the compiler, or use a precompiled header named VCxy.pch, if one exists. You can also control the name of the precompiled header that is created or used with the /Fp (Specify Precompiled Header Filename) option.
Use manual precompiling when you know that your source files use common sets of header files but don't include them in the same order, or when you want to include source code in your precompilation.
The manual precompiled-header options are /Yc (Create Precompiled Header File) and /Yu (Use Precompiled Header File). Use the /Yc option to create a precompiled header. When used with the optional hdrstop pragma, /Yc lets you precompile both header files and source code. Select the /Yu option to use an existing precompiled header in the existing compilation. You can also use the /Fp option with the /Yc and /Yu options to provide an alternative name for the precompiled header.
Building a PCH File
You can use one PCH to build another in a fairly simple way.
cl -c -Yc"stuff.h" -Fplevel1.pch level1.cpp cl -c -Yu"stuff.h" -Fplevel1.pch -Yc level2.cpp
level2.cpp file looks like this:
#include "stuff.h" #include "morestuff.h" #pragma hdrstop("level2.pch")
The following command will build
level2.pch, which can be used in further compiles:
cl -c -Yu"morestuff.h" -Fplevel2.pch mysource.cpp
Note that you only need to put the
#pragma hdrstop directive in the file that builds the second PCH; you don't have to put it in all .cpp files that use the PCH. Files that use the PCH can name the
morestuff.h file in the command line (so you don't have to edit all your files to use this). Either method of precompiling code — automatically or manually — stores the resulting precompiled code in a precompiled header.
- When to Precompile Source Code
- Debugging Code Compiled with Precompiled Headers
- Precompiled Header Consistency Rules
- Using Precompiled Headers in a Project
For further examples using precompiled headers, see the makefiles used to build the sample programs that ship with the Microsoft Foundation Class Library.