Alex Rivera | Logout

Should I put many functions into one file? Or, more or less, one function per file?

Asked 2009-02-10T05:20:08.533
10

Ideally I want one class per file or, when I have non-member functions, one function per file. The reasons are:

  1. When I read the code I will always know in what file I should find a certain function or class.
  2. If it's one class or one non-member function per header file, then I won't include a whole mess when I include a header file.
  3. If I make a small change in a function then only that function will have to be recompiled.

However, splitting everything into many header and implementation files can slow down compilation. Most functions access a number of templated other library functions so that code will be compiled over and over, once for each implementation file. Compiling my whole project takes 45 minutes. There are about 50 object files; each uses the same expensive-to-compile headers.

Is it acceptable to have one class (or non-member function) per header file, but putting the implementations of many or all of these functions into one implementation file, like in the following example?

// foo.h
void foo(int n);

// bar.h
void bar(double d);

// foobar.cpp
#include <vector>
void foo(int n) { std::vector<int> v; ... }
void bar(double d) { std::vector<int> w; ... }

Again, the advantage would be that I can include just the foo function or just the bar function, and compilation of the project will be faster because foobar.cpp is one file, so the std::vector<int> (just an example for some other expensive-to-compile templated construction) has to be compiled only once, as opposed to twice if I compiled a foo.cpp and bar.cpp separately. Of course my reason (3) is not valid for this scenario: After just changing foo(){...} I have to recompile the whole file foobar.cpp.

I'm curious what your opinions are!

Edit
Report

1 Answer

1

I also tried to split files in a function per file, but it had some drawbacks. Sometimes functions tend to get larger than they need to (you don't want to add a new .c file every time) unless you are diligent about refactoring your code (I am not).

Currently I put one to three functions in a .c file and group all the .c files for a functionality in a directory. For header files I have Funcionality.h and Subfunctionality.h so that I can include all the functions at once when needed or just a small utility function if the whole package is not needed.

answered 2009-02-10T05:36:08.527

Your Answer