It is conventional; both practices are used : small C++ files with one file per class, or large C++ files with several related classes and functions.
I don't recommend putting in C++ each class in its separate source and header file (this is nearly required by Java, not in C++). I believe that a class belongs conceptually to some "module" (and often a "module" contains several related classes and functions).
So I suggest declaring related classes of the same "module" in the same header file (e.g. foo.hh
), and implementing these classes in related (or same) code files (e.g. one foo.cc
or several foo-bar.cc
& foo-clu.cc
& foo-dee.cc
), each of them #include
-ing foo.hh
You usually want to avoid very short C++ files (to avoid huge build time). So I prefer having code files of several thousand lines, and header files of several hundred lines. In small sized applications (e.g. less than 30 thousand lines of code), I might have a single common header file. And a "module" (currently this is only a design, no C++11 feature explicitly supports modules) is often made of several related classes and functions. So I find that a source file implementing a "module" with several classes is more readable & maintainable than several tiny source files.
There is a reason to avoid very short source code files (e.g. of a hundred lines of code). Your C++ program will use standard C++ template containers, so will #include
-directly or indirectly- several standard headers like <string>
, <vector>
, <map>
, <set>
, etc.... In practice, these headers may bring thousands of lines (which the compiler will parse). For instance including both <vector>
and <map>
brings 41130 lines on my GCC 4.9. So a source file of a hundred lines including just these two headers takes a significant amount of time to be compiled (and you generally need to include standard containers in your header file). Hence a program with ten source files of a few thousands lines each will build faster than the same program organized in hundreds of source files of a few hundred lines each. Look into the preprocessed form of your code obtained using g++ -Wall -C -E
!
Future versions of C++ might have proper modules (the C++ standardization committee has and will discuss that, see e.g. n4047). Today C++11 don't have them, so I quoted "modules". Some languages (Go, Rust, Ocaml, Ada, ...) already have proper modules. And a module is generally made of several related classes, types, functions, variables.
Some C++ compilers are able to pre-compile header files. But this is compiler specific. With g++
it works well only if you have one single common header file. See this answer.
BTW, you should look into existing free software C++ code. Some projects have lots of small files, others have fewer but larger files. Both approaches are used!