1

I was recently looking through the source code of a C++ application and saw that each class did not #include its needed components, but instead #include'd a "Precompiled.h" header. In this Precompiled header was an inclusion of almost every header in the application (not all of them, it was clear that the length and order of the list was deliberate). Essentially, this would mean that every class had an inclusion of every other class in the application.

Is this wise? Why or why not?

benny.bennett
  • 700
  • 1
  • 8
  • 25
  • 2
    It's worth doing only for large headers that rarely change. E.g. some system headers. By precompiling them you can speed up the compilation. – v154c1 Sep 08 '13 at 15:12

2 Answers2

3

Usually if you write an application, you should only include header files which are really needed in cpp files. If you got a really big application, you should use forward declaration in the header and include necessary files in the cpp file. With that, changes in code only affects a minimum on cpp files, so the compiler had only to compile what really has changed. The situation can totally flip, when it comes to libraries or code which does not change very often. The filename "Precompiled.h" is already a hint. The compiler can precompile the headers to a special object file, often called PCH file. With that, the compiler has not to resolve every include on every compile time. On heavy nested includes, this has high impact on compile speed, because instead of many files to load and parse, there is only one preparsed file. To archive that you have to declare one or more headers as a kind of center file for building a precompiled header. How you do that differs between different compilers. For example Visual studio uses the header file "stdafx.h" as the center of the precompilation of header files. Because of that, only header files should include there which are not altered very often. Also the file had to be included first in every cpp file. That is because the compiler can not detect any more if a include file which is included before may have influence to the precompiled file. To avoid that, includes before the precompiled includes are not allowed.

Back to your question. Including every file in one header file to use it as precompiled header makes no sense at all, as it conteract the meaning of a precompiled header file.

Martin Schlott
  • 4,369
  • 3
  • 25
  • 49
1

It is a very bad idea.

For a .cpp file only include the minimum number of #include files.

Thereby when one of them changes the make (or moral equilivant) will not require the whole lot to be recompiled.

Saves lots of time during development.

PS Use forward declarations in preference to #include

Ed Heal
  • 59,252
  • 17
  • 87
  • 127