I have already argued that you shouldn’t put all your includes in your .h files. Here is one more reason, compilation time.
Have a look at this example, where the arrows mean “includes”
file5.h apparently need access to something which is defined in
file4.h, which again needs access to three other headers. Because of this, all other files that include
file5.h also includes
#include "file.h" really means “copy the entire contents of
file.h here before compiling”. So in this example,
file[1-3] is copied into
file4.h, which is then copied into
file5.h, which again is copied into the three
cpp files. Every file takes a bit of time to compile, and now each
cpp file doesn’t only need to compile its own content, but also all of the (directly and indirectly) included headers. What happens if we add some compilation times to our diagram? The compilation time of the file itself is on the left, the compilation time including the included headers are on the right.
As we can see, this has a dramatic effect on compilation time.
file7.cpp just needed something from
file5.h, but got an entire tree of headers which added 1.2 seconds to their compilation times. This might not sound much, but those numbers add up when the number of files is large. Also, if you’re trying to do TDD, every second counts. And in some cases, compilation times of individual headers can be a lot worse than in this example.
file5 didn’t really need to have
#include "file4.h" in the header, but could move it to the source file instead? Then we would have this diagram:
The compilation time of
file[6-7].cpp is significantly reduced.
Now let’s look at what happens if a header file is modified. Let’s say you need to make a minor update in
file1.h. When that file is changed, all the files that include it need to be recompiled as well:
But if we were able to
#include "file4.h" in
file5.cpp instead of
file5.h, only one cpp file would need to recompile:
Recompilation time: 1.7 seconds vs. 4.5 seconds. And in a large project, this would be a lot worse. So please try to move your
#includes down into the cpp files whenever you can!
The Graphviz code and makefile for this blog post is available on GitHub.