Search code examples
c++performancefile-organization

Multiple classes in a header file vs. a single header file per class


For whatever reason, our company has a coding guideline that states:

Each class shall have it's own header and implementation file.

So if we wrote a class called MyString we would need an associated MyStringh.h and MyString.cxx.

Does anyone else do this? Has anyone seen any compiling performance repercussions as a result? Does 5000 classes in 10000 files compile just as quickly as 5000 classes in 2500 files? If not, is the difference noticeable?

[We code C++ and use GCC 3.4.4 as our everyday compiler]


Solution

  • The term here is translation unit and you really want to (if possible) have one class per translation unit ie, one class implementation per .cpp file, with a corresponding .h file of the same name.

    It's usually more efficient (from a compile/link) standpoint to do things this way, especially if you're doing things like incremental link and so forth. The idea being, translation units are isolated such that, when one translation unit changes, you don't have to rebuild a lot of stuff, as you would have to if you started lumping many abstractions into a single translation unit.

    Also you'll find many errors/diagnostics are reported via file name ("Error in Myclass.cpp, line 22") and it helps if there's a one-to-one correspondence between files and classes. (Or I suppose you could call it a 2 to 1 correspondence).