5.2 Multiple source files

If a program only needs one source (.c or .cc) file, there is little need to create user header files. In a realistic project, however, there are many source files. The use of multiple source files means that source code is more modular. This, in return, means that a source file can be reused in multiple projects, thus saving significant development time.

Multiple source file also means better organization, which makes maintenance easier in the long run. If everything is lumped into one source file, it becomes more difficult to locate definitions and edit contents in the file.

In C and C++, there is no restriction of how much, or how little you can put in a source file. If you want to, you can define a single function in each source file. Of course, you'll end up with many source files, which may defeat the ``easy maintenance'' objective. The granularity of source files is, for the most part, at the discretion of individual programmers.

In C++ programming, however, it is common to keep all definitions related to a class in the same file. This is not a mandatory requirement. You can, if you want to, define a single method (member function) in its own file. However, because methods can refer to each other, it makes sense to put them into the same file.

Copyright © 2006-09-07 by Tak Auyeung