Include std library in header or cpp?

user695652 picture user695652 · Oct 12, 2011 · Viewed 32.7k times · Source

If I have a class A which uses iostream, should I put the include statement of iostream in A.h or A.cpp?

Answer

Jerry Coffin picture Jerry Coffin · Oct 12, 2011

This is an area of some controversy. My own preference is that each header should be able to stand alone, so if it needs other headers, it includes them. In other words, if client code is going to need to include <iostream> (or whatever) anyway, your header should handle that for them. OTOH, if the user of the iostream is strictly hidden so the client code doesn't need to include it at all, then it should only be included in the implementation file.

In many cases (especially where the header is open to frequent change), you'd prefer to avoid including it in the header. In such cases, the PImpl idiom can be useful to get the dependency out of the header.

If you do need to include <iostream>, do your clients a favor and consider whether you can #include <iosfwd> instead of <iostream> though. This can improve compile time a fair amount.