#include Guidelines

— richardwb on Monday, June 22, 2009 @ 19:20

This is mostly for my own reference, but here are some of the guidelines I like to follow when it comes to #includes in C++. Given foo.cpp and foo.h:

  • foo.h should include everything it mentions and no more. For example, if you use boost::random in the implementation, don't #include <boost/random.hpp> in foo.h.

  • foo.cpp should also include everything it mentions and no more.

  • foo.cpp's first include should be #include "foo.h".

  • Precompiled headers, if used, should be specified in foo.cpp only and will need to be the first #include (#include "foo.h" will then be the second).

  • Except for the above two exceptions, the order I like to follow for #includes is:

    1. Headers from your own project (generally of the form #include "baz.h")
    2. Headers from non-standard libraries (such as Qt)
    3. Standard libraries (I include Boost in here because I use it so pervasively)
    4. Platform headers (like #include <windows.h>)
  • Within each of the above groups try to alphabetically order the #includes if at all possible.

  • Forward declare whenever you can get away with it.

comments powered by Disqus