I recently posted a question asking for what actions would constitute the Zen of C++. I received excellent answers, but I could not understand one recommendation:
- Make header files self-contained
How do you ensure your header files are self-contained?
Any other advice or best-practice related to the design and implementation of header files in C/C++ will be welcome.
Edit: I found this question which addresses the "Best Practices" part of mine.
A self-contained header file is one that doesn’t depend on the context of where it is included to work correctly. If you make sure you #include or define/declare everything before you use it, you have a self-contained header.
An example of a non self-contained header might be something like this:
In this example, MyClass.h uses
std::stringwithout first #including <string>.For this to work, in MyClass.cpp you need to put the
#include <string>before#include "MyClass.h".If
MyClass‘s user fails to do this he will get an error that std::string is not included.Maintaining your headers to be self-contained can be often neglected. For instance, you have a huge
MyClassheader and you add to it another small method which usesstd::string. If in all places this class is currently used, <string> is already #included before MyClass.h, then someday you will #include MyClass.h as the first header and suddenly you have this new error in a file you didn’t even touch (MyClass.h).Carefully maintaining your headers to be self-contained helps to avoid this problem.