Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does precompiled header reduce compile time

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?

like image 866
Drahakar Avatar asked Nov 28 '11 04:11

Drahakar


2 Answers

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.

like image 62
Drahakar Avatar answered Oct 23 '22 10:10

Drahakar


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).

like image 23
André Caron Avatar answered Oct 23 '22 11:10

André Caron