5
votes

I've been using precompiled header for a while and been told (and saw) how they can reduce compile time. But I would really like to know what is going on (under the hood) so it can make my compilation faster.

Because from what I know, adding unused include in a .cpp can slower your compile time, and a header file can contain a lot of unused header to a .cpp.

So how does a precompiled header make my compilation faster?

4

4 Answers

4
votes

From http://gamesfromwithin.com/the-care-and-feeding-of-pre-compiled-headers Thank you (@Pablo)

A C++ compiler operates on one compilation unit (cpp file) at the time. For each file, it applies the pre-preprocessor (which takes care of doing all the includes and “baking” them into the cpp file itself), and then it compiles the module itself. Move on to the next cpp file, rinse and repeat. Clearly, if several files include the same set of expensive header files (large and/or including many other header files in turn), the compiler will be doing a lot of duplicated effort.

The simplest way to think of pre-compiled headers is as a cache for header files. The compiler can analyze a set of headers once, compile them, and then have the results ready for any module that needs them.

2
votes

Basically, a header file is compiled once for each translation unit (.cpp file) by which it is included. Using a pre-compiled header header saves on time used to compile an include file over and over again. This is really beneficial when the header file to be pre-compiled is very large (or indirectly includes many other header files).

1
votes

Many years ago I had access to a C compiler that printed out the number of lines it processed (Watcom C version 6 or so). Compiling files with less than 100 lines of C code would display counts of 5,000 or even 10,000 lines. All of which were #included. In other words #included code completely dominates compilation time. So anything you can do to reduce that is going to be beneficial. You can see for yourself with compilers that allow you to disable preprocessing: compare the times for complete system builds with and without it.

0
votes

I think the "precompiled" says something about how it makes compilation faster. You can read about the basic concept here I think:

http://en.wikipedia.org/wiki/Precompiled_header