I\'m new to programming and the topic of header files is sort of bogging me down after I started using a lot of them. In addition to that I\'m trying to use precompiled headers.
My philosophy is that in well-written code, header files should include all other header files that they depend on. My reasoning is that it should not be possible to include a header file and get a compiler error for doing so. Therefore, each header file should (after the #ifdef
or #pragma once
include guard) include all other headers it depends on.
In order to informally test that you've remembered to include the right headers in your header files, *.cpp files should #include the minimum set of header files that should work. Therefore, if there are separate header files for A
, B
, C
and D
, and your cpp file uses class D
, then it should only include D.h. No compiler errors should result, because D.h #include
s A.h and C.h, C.h includes B.h, and A.h and B.h include the SFML header (whatever that is). C.h and D.h can include the SFML header if it seems appropriate, but it's not really necessary, if you can be sure that the dependencies (B.h and A.h) already included it.
The way Visual C++ does "precompiled headers" screws up this logic, however. It requires you to include "StdAfx.h"
as the very first header file, which causes many developers to simply put all #include
s for the entire project in StdAfx.h, and not to use #include
in any of the other header files. I don't recommend this. Or, they will put all external dependencies in StdAfx.h (e.g. windows.h, boost headers) and #include the local dependencies elsewhere so that changing a single header file does not necessarily cause the entire project to rebuild.
The way I write my code, most of my CPP files include StdAfx.h, and the corresponding .H file. So A.cpp includes StdAfx.h and A.h, B.cpp includes StdAfx.h and B.h, and so forth. The only other #include
s placed in a cpp file are "internal" dependencies that are not exposed by the header file. For example, if class A
calls printf()
, then A.cpp (not A.h) would #include
, because A.h does not depend on stdio.h.
If you follow these rules then the order that you #include
headers does not matter (unless you use precompiled headers: then the precompiled header comes first in each cpp file, but does not need to be included from header files).