Saturday, September 13, 2008

C++ Coding Standard: Header File Layout

Section 2 of the C++ code standard specifies how the header file for a class is structured. As the specification of the class, the header file should be uncluttered and easy to navigate. Section 7 will go into more details about how to organize the class definition itself. This general outline can still be followed, for those few project headers which don't define a class.
  • 2.1. Header files must begin with the standard C++ file comment.
  • 2.2. Then comes the "#ifndef" of the include guard.
    • 2.2.1. Guard macro format _<DIR>_<CLASS>_H (all caps).
  • 2.3. Then include directives and external class declarations (optional).
  • 2.4. Then outside-the-class typedefs (optional).
  • 2.5. Then the class definition.
  • 2.6. Then other interface declarations (optional).
  • 2.7. Then inline function definitions (optional).
  • 2.8. Then the "#endif" of the include guard.
The standard file comment usually contains your company or organization name and copyright statement. Even if you don't require those items, at least you should have an ID string to be expanded by your version control system -- for subversion and RCS/CVS a good choice is $Id:$.

You can choose whatever format for the include guard makes sense for you; I suggest including the directory name, in case the unthinkable happens and your project ends up with two files with the same name. Incidentally, don't use external include guards -- they solve a problem that doesn't exist while cluttering your source files.

Next: header file contents.

No comments: