Organizing C/C++ includes

After starting my new job programming in a big software project I spent some thought on organizing includes and give a recommendation. Here’s what I’ve come up with. As always, some things are obvious, some are not…

  1. You should only include what is necessary to compile the source code. Adding unnecessary
    includes means a longer compilation time, especially in large projects.
  2. Each header and corresponding source file should compile cleanly on its own. That
    means, if you have a source file that includes only the corresponding header, it
    should compile without errors. The header file should include not more
    than what is necessary for that.
  3. Try to use forward declarations as much as possible. If you’re using a
    class, but the header file only deals with pointers/references to
    objects of that class, then there’s no need to include the definition of
    the class. That is what forward declarations are designed for!

    // Forward declaration

    class MyClass;

  4. Note that some system headers might include others. But apart from a few
    exceptions, there is no requirement. So if you need both
    <iostream> and <string> include both, even if you can
    compile only with one of them.
  5. To prevent multiple-inclusions, with loops and all such attendant horrors is having an #ifndef guard.

    #ifndef _FOO_H
    #define _FOO_H
      …contents of header file…
    #endif

  6. The order in which the includes appear (system includes and user includes) is up to the coding standard you follow.
  7. If you have the choice of picking a coding standard regarding the order at the beginning of a new project, I recommend to go from local to global, each
    subsection in alphabetical order. That way you can avoid introducing
    hidden dependencies. If you reverse the order and i.e. myclass.cpp
    includes <string> then <myclass.h>, there is no way to catch
    at build time that myclass.h may itself depend on string. So if later someone includes myclass.h but does not need string, he’ll
    get an error that needs to be fixed either in the cpp or in the header
    itself. 
  8. So the recommended order would be:
    • header file corresponding to its .cpp file
    • headers from the same component
    • headers from other components
    • system headers

If you use the Eclipse IDE (which I highly recommend), you can use a very nice feature that helps you organizing includes (“Source -> Organize Includes”).