Header-only libraries

Mar 3, 2024    #c   #c++  

Header-only libraries are one of the best ways to handle C/C++ external dependencies. They greatly simplify developing and managing external dependencies. To my knowledge, they were first introduced by Sean Barret, the programmer responsible for the renderer of games such as Thief, Thief 2, and System Shock 2.

When using a header-only library, the programmer declares the guarding defintion before including the header file in a single .c or .cpp file.

The typical header-only library has the following structure:

#pragma once

// Declarations
struct SomeData
{
  // ...
};

int someVariable;

void some_function();
void some_other_function();

// The implementation guard
# ifdef LIBRARY_IMPLEMENTATION
static void some_function()
{
  // do something
}

static void some_other_function()
{
  // do something
}
# endif // LIBRARY_IMPLEMENTATION

I’ve written a couple of my own header-only libraries and intend to write many more. They are linked in the Resources section. Feel free to check them out for a more robust example.

When using a header-only library in a larger project with multiple files, you would first create a library_name.c file and populate it like so:

#define LIBRARY_IMPLEMENTATION
#include "library.h"

Then you can include library.h in as many source files as necessary to make use of its features.

If the project is small (or you, like me, prefer single source file large projects), you can just add the definition declaration and the include directly in your main source file.

Resources