I'm cleaning up the includes in a C++ project I'm working on, and I keep wondering whether or not I should explicitly include all headers used directly in a particular file, or whether I should only include the bare minimum.
Here's an example, Entity.hpp
:
#include "RenderObject.hpp"
#include "Texture.hpp"
struct Entity {
Texture texture;
RenderObject render();
}
(Let's assume that a forward declaration for RenderObject
is not an option.)
Now, I know that RenderObject.hpp
includes Texture.hpp
– I know that because each RenderObject
has a Texture
member. Still, I explicitly include Texture.hpp
in Entity.hpp
, because I'm not sure if it's a good idea to rely on it being included in RenderObject.hpp
.
So: Is it good practice or not?
Best Answer
You should always include all headers defining any objects used in a .cpp file in that file regardless of what you know about what's in those files. You should have include guards in all header files to make sure that including headers multiple times does not matter.
The reasons:
Texture
objects in this file.RenderObject.hpp
doesn't actually needTexture.hpp
itself.A corollary is that you should never include a header in another header unless it is explicitly needed in that file.