Search code examples
c++headercoding-styleproject-structure

Are functions in C/C++ headers a no-go?


I'm working on a very tiny piece of C/C++ source code. The program reads input values from stdin, processes them with an algorithm and writes the results to stdout.

I would just implement all that in a single file, but I also want test cases for the algorithm (not the input/output reading), so I have the following files in my project:

  • main.cpp
  • sort.hpp
  • sort_test.cpp

I implement the algorithm in sort.hpp right away, no sort.cpp. It's rather short and doesn't have any dependencies.

Would you say that, in some cases, functions defined in headers are okay, even if they are sophisticated algorithms and not just simple accessors/mutators? Or is there a reason I should avoid this? When should I move code from header to source file?


Solution

  • The vast majority of the boost libraries are header-only, so I'd say: Yes, this is an established and accepted practice. Just don't forget to inline.