Header only libraries in C++

A header-only library is a library where the entire definition is available in the header files. Hence, we don't need to link to a separate library when building the executable. Header-only libraries are often used for small libraries or for libraries that are not intended to be used outside of the project.

These are generally preferred for template based libraries where the final code is not known until the template is instantiated. In template based libraries, entire code lives in header file, this allows code to be generated based on the type which is being used

Pros:

  • Ease of use, All we need to do is to include the header file and we are good to go
  • From library provider perspective, it is easier to maintain and distribute, since entire code base is in a same location, it becomes convenient to add new features

Cons:

  • Extended compilation times, because for templated libraries, code needs to be generated on the fly based on the type being used, this will happen every time the implementation file which includes the library is compiled

For example, nanobench is a microbenchmarking library for C++ which is available as header only library, https://github.com/martinus/nanobench