Self Contained Headers

In CeePlusPlus, SelfContainedHeaders are header files that can be included top-most in a translation unit, i.e. that do not rely on other headers that have to be included before them.

To check that a header is self-contained, include it topmost in the module that implements it, i.e.

foo.cpp:

  // top of file
  #include "foo.h"
  // ... other includes

To make a header self-contained, make sure that it includes any header files it needs:

foo.h:

  #ifndef FOO_H
  #define FOO_H
  #include "bar.h"
  class Foo : public Bar {};
  #endif

And make sure that those header files use IncludeGuards:

bar.h:

  #ifndef BAR_H
  #define BAR_H
  class Bar {}; 
  #endif

The goal with headers is to reduce interdependencies, so you should also consider using ForwardDeclarations to avoid having to include the other headers at all. (See the PimplIdiom)

Suppose that the header was not self contained. Then if you wish to use refer to the symbols declared in that header in a different client, then the new client wouldn't even compile unless you found and pulled the need other headers.

The #include's also for a strong marker to the readers of the program as to which other modules are required to compile (and use) this routine.

A related notion is that headers should be necessary. ie. Only those headers required to compile _this_ header should be included. You do your clients a disservice to #include other headers you think they may need.


To speed up compile times, you may desire to use RedundantIncludeGuards as well as ordinary IncludeGuards.

The number of includes another one depends on is normally very low, and thus the negative effects of RedundantIncludeGuards are reduced. The positive effects are higher, because an implementation file is translated only once, but a header is used quite often. Making them self-contained leads to more includes in includes in includes... which enforces the positive effects even more.

In an IdealWorld?, all this would of course be not necessary.


CategoryCpp


EditText of this page (last edited July 15, 2013) or FindPage with title or text search