suppose I have a header foo.h
like this:
#ifndef FOO_H
#define FOO_H
#include
#include \"non_standard_class.h\"
std::string foo(
The practice I follow:
#include <string>
if there is std::string
in foo.h)Another formulation of this practice: in foo.*, include only those headers the source code needs. If a header is needed by only foo.cpp (but not by foo.h), then include it from foo.cpp, otherwise include it from foo.h.
So, in your case, I wouldn't #include <string>
in foo.cpp, because it's already included by foo.h.
Let's assume that string
does an #include <vector>
, and foo.h contains std::vector
. In this case, I'd #include <vector>
in foo.h, because its source code needs it – and it doesn't matter that string
already includes it.
I would say it is, because otherwise your foo.cpp is relying on a detail of foo.h that may change. Obviously this is more of a problem with other .h files that aren't under your control, but I still do it for consistency sake.
Personally I follow the (questionable) minimal inclusion practice: I only include what's needed for compilation to work.
People telling to get a better compiler / machine quite make me laugh, in a way, the project I am working on daily is compiled in about 8 minutes (from scratch) on a quad-core (was about 1 hour before I scrapped down dependencies) and I find it too damn long. I certainly don't want any change to cause the whole thing to recompile, and therefore I am wary of any include.
During development, I always feel like compilation time is wasted time. A bit might allow a break sure, but when you want to test something now, it's only frustrating to wait for the damn thing to finally be ready (especially if it just blows in your hand when testing and you realize you'll have to modify it again and re-compile again).
Including things twice seems like a good way to forget to remove the include from the source when it's no longer need by the header (hurray for forward declaration), I don't see the point.