Hello, I'd like to know if it is considered bad practice to include a header (.h) in another header. Is it? Why?
Hello, I'd like to know if it is considered bad practice to include a header (.h) in another header. Is it? Why?
My opinion is like this.
My personnal rule is simple :
My headers are guarded (Like those from the library)
I include a header when I need it. (Can be in a source or a header)
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
No - it is not...I'd like to know if it is considered bad practice to include a header
I prefer header to be complete - so I can include it in any c-file without including any other header before it...
On the other hand - I prefer to make header dependencies - minimal, so If the forward declaration is enough - I use it rather to include the other header with the full type definition.
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler
My own preference is this:
Include my own needed headers from my headers (if A.h needs B.h, include B.h).
Any system headers (iostream, windows.h, dshow.h, etc, etc) are not included. The project that includes the header is expected to have put those headers inside its stdafx.h - precompiled header.
I think most people follow vart's usage. #include everything in your header that needs to be included so that it will compile no matter what. Prefer forward declarations over #include's when they will work.
If you use precompiled headers, then of course common headers placed there don't need to be included.
Thanks for the super fast replies, guys. I'll follow vart's (and others') advice.
No, not if the header file is directly using something declared in another header, otherwise, if it's only used in the implementation rather than the interface, the other headers should be included in the .cpp files.
Code:#ifndef MYCLASS_H #define MYCLASS_H #include <string> class MyClass { public: MyClass( const std::string& name ); // std::string is referenced here, so we need to include <string> ... }; #endif // MYCLASS_HCode:#include "MyClass.h" #include <algorighm> MyClass::MyClass( const std::string& name ) { // std::transform is only referenced in the .cpp file, so <algorithm> should be included here, not in the .h file. std::transform( name.begin(), name.end(), name.begin(), ToLowerFunc ); }