Self-sufficient header files in C/C++

A self sufficient 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 yourself a self sufficient header.
An example of a non self sufficient header might be something like this:

----- MyClass.h -----

class MyClass
{
   MyClass(std::string s);
};

---- MyClass.cpp -----

#include <string>
#include "MyClass.h"

MyClass::MyClass(std::string s)
{}

In this example, MyClass.h uses std::string without first #including .
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 sufficient can be often neglected. For instance, you have a huge MyClass header and you add to it another small method which uses std::string. In all of the places this class is currently used, is already #included before MyClass.h. then someday you #include MyClass.h as the first header and suddenly you have all these new error in a file you didn’t even touch (MyClass.h)
Carefully maintaining your headers to be self sufficient help to avoid this problem.

Leave a Comment