Thursday, 21 June 2007

Implementing header-only libraries in C++

Recently I have been investigating the feasibility of implementing a C++ curses library using only header files.

A header-only library is very simpler to use, as it does not require any object linking or dependencies. The relevant parts of the library are included entirely into the program itself. However, there are a few caveats:

  • We cannot use static variables, as their definitions will cascade to every object file that includes them. We could have the user define our internal static variables in their source files (perhaps with a macro for convenience), but I believe this is unreasonable and poor design.
  • Without static variables, our memory management options are limited, and we are prevented from using design patterns such as singletons.
  • The entire library is re-compiled each time with the program, causing it to take longer to compile.
  • If the implementation of our library changes, the entire program must be re-compiled to reflect the its changes.
  • The file size of the program will be greater because it includes the entire library.
  • Only private class members will be unavailable to the program. Everything else is open season.

I believe header-only libraries are well-suited where the ownership (including memory and lifetime management) of library objects lies with the user.