Thursday, September 11, 2008

C++ Coding Standard: Source Files

Since all of your code is in files, and since a lot of C++ code consists of class definitions and class implementations, a good place for a C++ coding standard to start is by specifying some rules for putting classes into files.

  • 1.1. Every class must have a header file called "{class}.hpp".
  • 1.2. Every class must have an implementation file called "{class}.cpp".
    • 1.2.1. Exception to 1.2: template class with only inline members.
    • 1.2.2. Exception to 1.1 and 1.2: class in anonymous namespace.
  • 1.3. {class}.hpp and {class}.cpp must be in the same directory.
  • 1.4. {class}.hpp must define one and only one class.
    • 1.4.1. Exception to 1.4: nested classes or structs.
  • 1.5. Filenames must match the class names exactly, including case.
These rules haven't addressed directory structure at all, and there's a lot of advice that could be given about that. But those issues usually get tackled at the beginning of the project, and sit at the intersection of software architecture and build/release processes. The above rules help with an issue that comes up frequently: where to put a new class.

The rationale for the one class == one header + one implementation is simple: so that when I need to look at or change a given class later, I know exactly which file it is in.

Next up: header file layout.


Stumble Upon Toolbar

No comments: