andersch.dev

<2023-04-06 Thu>
[ c ]

Header-only Libraries

Header-only libraries are a form of software libraries that are popular in C and C++ programming.

Principles for writing good libraries

See: How to write better (game) libraries

Core principles:

  • Maximize portability.
  • Be easy to build.
  • Be easy to integrate.
  • Be usable in as many scenarios as possible.

More specifically:

  • Consider writing the library in C and add wrappers to other languages later.
  • Consider providing an optional C++ wrapper.
  • Try not to make the use of a build system mandatory.
  • Ensure that people can easily compile the library from source.
  • Minimize dependencies.
  • Try not to allocate memory for the user.
  • Be const correct.
  • Always ask for the size of buffers (even for const char*)
  • Try not to handle resources for user.
  • Avoid using os-dependent functions (such as fopen) for maximum portability.
  • Don't load OpenGL in the library if you depend on it.
  • Provide examples.
  • Use namespace prefixes.
  • Avoid global variables if possible.
  • Consider what error handling strategy you will use.
  • Consider your distribution model.

Examples of good libraries:

Resources