[ACCEPTED]-How to use precompiled headers efficiently (using /Yc and Yu options)?-precompiled-headers

Accepted answer
Score: 23

The problem

Let's say you have a list of headers you 30 use that you know won't change. For example, the 29 C headers, or the C++ headers, or Boost 28 headers, etc..

Reading them for each CPP 27 file compilation takes time, and this is 26 not productive time as the compiler is reading 25 the same headers, again and again, and producing 24 the same compilation result for those same 23 headers, again and again.

There should be 22 some way to tell the compiler those headers 21 are always the same, and cache their compiled 20 result instead of recompiling them again 19 and again, no?

The solution

The Pre-Compiled Headers takes 18 that into account, so all you need is to:

  1. Put all those common and unchanging includes in one header file (say, StdAfx.h)
  2. Have one empty CPP file (say, StdAfx.cpp) including only this one header file

And 17 now, what you need is tell the compiler 16 that StdAfx.cpp is the empty source that 15 includes the common and unchanging headers.

This 14 is where the flags /Yc and /Yu are used:

  • Compile the StdAfx.cpp file with the /Yc flag
  • Compile all the others CPP files with the /Yu flag

And 13 the compiler will generate (when needed) a 12 pre-compiled header file from the StdAfx.cpp 11 file, and then reuse this pre-compiled header 10 file for all other files marked with /Yu.

Note

When 9 you create a new project, old versions of 8 Visual C++ (6 and 2003, if I remember correctly) would 7 activate the precompiled headers by default. Recent 6 ones offer the choice of activating them 5 of not.

You should create a new VC++ project 4 with the PCH activated to have a working 3 version of PCH-enabled project, and study 2 the compilation options.

For more information 1 about PCH, you can visit the following URL:

Score: 2

/Yc should only be used on one of your .cpp 5 modules. This specifies to VS to create 4 the precompiled header with that module.

For 3 all others in your project, use /Yu. This 2 specifies that they are to simply use the 1 pch.

The MSDN entry for it is here: http://msdn.microsoft.com/en-us/library/szfdksca(v=VS.71).aspx

More Related questions