name: c-single-header description: Single-header library pattern — implementation guard, header-before-data, type-generic API, allocator override. Use when: creating distributable C libraries, STB-style headers. license: MIT
Single-Header Libraries
Single-header libraries are distributed as one .h file that acts as both
header and implementation. Users drop in the file with zero build system
changes.
Popularized by Sean Barrett's stb libraries (stb_image, stb_ds, etc.).
Implementation Guard Pattern
The user defines an implementation macro in exactly one translation unit.
Pattern
// mylib.h
#ifndef MYLIB_H
#define MYLIB_H
// ============== DECLARATIONS ==============
// (Included in all translation units)
typedef struct MyLibContext MyLibContext;
MyLibContext *mylib_create(void);
void mylib_destroy(MyLibContext *ctx);
int mylib_process(MyLibContext *ctx, const void *data, size_t size);
// ============== IMPLEMENTATION ==============
// (Included in exactly one translation unit)
#ifdef MYLIB_IMPLEMENTATION
#include <stdlib.h>
#include <string.h>
struct MyLibContext {
int state;
char buffer[1024];
};
MyLibContext *mylib_create(void)
{
MyLibContext *ctx = malloc(sizeof(*ctx));
if (ctx) {
memset(ctx, 0, sizeof(*ctx));
}
return ctx;
}
void mylib_destroy(MyLibContext *ctx)
{
free(ctx);
}
int mylib_process(MyLibContext *ctx, const void *data, size_t size)
{
// Implementation...
return 0;
}
#endif // MYLIB_IMPLEMENTATION
#endif // MYLIB_H
User Code
// main.c
#define MYLIB_IMPLEMENTATION // Define BEFORE include in ONE file
#include "mylib.h"
int main(void)
{
MyLibContext *ctx = mylib_create();
mylib_process(ctx, "hello", 5);
mylib_destroy(ctx);
return 0;
}
Header-Before-Data Pattern
Store metadata at negative offsets so the user gets a clean pointer to element 0.
Dynamic Array
// stb_ds style
typedef struct {
size_t length;
size_t capacity;
void *hash_table; // For hash maps
} stbds_array_header;
#define stbds_header(a) ((stbds_array_header *)(a) - 1)
// User declares as null pointer
int *arr = NULL;
// Internal: get length from header
size_t arrlen(int *a) {
return a ? stbds_header(a)->length : 0;
}
// Internal: grow and return pointer
void *stbds_arrgrowf(void *a, size_t elemsize, size_t addlen, size_t min_cap);
// User macro: append element
#define arrput(a, v) \
(stbds_arrmaybegrow(a, 1), \
(a)[stbds_header(a)->length++] = (v))
Usage
int *arr = NULL; // Null IS the empty array
arrput(arr, 10);
arrput(arr, 20);
arrput(arr, 30);
for (size_t i = 0; i < arrlen(arr); i++) {
printf("%d\n", arr[i]);
}
arrfree(arr); // Frees header + data
Allocator Override
Allow users to provide custom allocation functions.
Pattern
// mylib.h
#ifndef MYLIB_MALLOC
#define MYLIB_MALLOC(size) malloc(size)
#endif
#ifndef MYLIB_REALLOC
#define MYLIB_REALLOC(ptr, size) realloc(ptr, size)
#endif
#ifndef MYLIB_FREE
#define MYLIB_FREE(ptr) free(ptr)
#endif
// Use throughout implementation
#ifdef MYLIB_IMPLEMENTATION
void *mylib_alloc(size_t size)
{
void *ptr = MYLIB_MALLOC(size);
if (!ptr) {
// Handle allocation failure
}
return ptr;
}
void *mylib_realloc(void *ptr, size_t size)
{
return MYLIB_REALLOC(ptr, size);
}
void mylib_free(void *ptr)
{
MYLIB_FREE(ptr);
}
#endif
User Override
// User's custom allocator
void *my_malloc(size_t size) { return arena_alloc(size); }
void my_free(void *ptr) { /* no-op with arena */ }
// Override before including
#define MYLIB_MALLOC(size) my_malloc(size)
#define MYLIB_FREE(ptr) my_free(ptr)
#define MYLIB_IMPLEMENTATION
#include "mylib.h"
Context-Based Allocator
For libraries that need context:
typedef void *(*MyLibAllocFunc)(void *user, size_t size);
typedef void (*MyLibFreeFunc)(void *user, void *ptr);
typedef struct {
MyLibAllocFunc alloc;
MyLibFreeFunc free;
void *user_data;
} MyLibAllocator;
MyLibContext *mylib_create_with_allocator(MyLibAllocator *alloc);
Type-Generic API
Macros that work on any type without templates.
Size Inference
// Derive element size from pointer type
#define arrlen(a) \
((a) ? (ptrdiff_t)stbds_header(a)->length : 0)
#define arrsetcap(a, n) \
((a) ? stbds_arrgrow(a, n, sizeof(*(a))) : 0)
#define arrput(a, v) \
(stbds_arrmaybegrow(a, 1, sizeof(*(a))), \
(a)[stbds_header(a)->length++] = (v))
typeof Extension (GCC/Clang)
#ifdef __GNUC__
#define MYLIB_HAS_TYPEOF 1
#else
#define MYLIB_HAS_TYPEOF 0
#endif
#if MYLIB_HAS_TYPEOF
#define MYLIB_SWAP(a, b) do { \
typeof(a) _tmp = (a); \
(a) = (b); \
(b) = _tmp; \
} while (0)
#else
#define MYLIB_SWAP(a, b) do { \
char _tmp[sizeof(a)]; \
memcpy(_tmp, &(a), sizeof(a)); \
memcpy(&(a), &(b), sizeof(a)); \
memcpy(&(b), _tmp, sizeof(a)); \
} while (0)
#endif
Name Decoration
Allow users to customize symbol names to avoid conflicts.
#ifndef MYLIB_PREFIX
#define MYLIB_PREFIX mylib_
#endif
#define MYLIB_PASTE(a, b) a ## b
#define MYLIB_XPASTE(a, b) MYLIB_PASTE(a, b)
#define MYLIB_SYM(name) MYLIB_XPASTE(MYLIB_PREFIX, name)
// All public symbols use MYLIB_SYM
typedef struct MYLIB_SYM(Context) MYLIB_SYM(Context);
MYLIB_SYM(Context) *MYLIB_SYM(create)(void);
void MYLIB_SYM(destroy)(MYLIB_SYM(Context) *ctx);
User Customization
#define MYLIB_PREFIX myapp_
#define MYLIB_IMPLEMENTATION
#include "mylib.h"
// Now symbols are myapp_create, myapp_destroy, etc.
C++ Wrappers
Provide type-safe overloads for C++ users.
#ifdef __cplusplus
// Disable C++ overloads
#ifndef MYLIB_NO_CPP_WRAPPERS
// Template wrapper for type safety
template<typename T>
class MyLibArray {
T *data;
public:
MyLibArray() : data(NULL) {}
~MyLibArray() { MYLIB_SYM(arrfree)(data); }
void push(const T &value) {
data = (T *)MYLIB_SYM(arrgrow)(data, sizeof(T), 1);
data[MYLIB_SYM(arrlen)(data)] = value;
}
T& operator[](size_t i) { return data[i]; }
size_t size() const { return MYLIB_SYM(arrlen)(data); }
};
#endif // MYLIB_NO_CPP_WRAPPERS
#endif // __cplusplus
Configuration Macros
Let users configure behavior at compile time.
// Assertions
#ifndef MYLIB_ASSERT
#include <assert.h>
#define MYLIB_ASSERT(x) assert(x)
#endif
// Logging
#ifndef MYLIB_LOG
#define MYLIB_LOG(...) ((void)0)
#endif
// Inline control
#ifndef MYLIB_INLINE
#ifdef _MSC_VER
#define MYLIB_INLINE __forceinline
#else
#define MYLIB_INLINE static inline __attribute__((always_inline))
#endif
#endif
// Debug checks
#ifdef MYLIB_DEBUG
#define MYLIB_CHECK(x) MYLIB_ASSERT(x)
#else
#define MYLIB_CHECK(x) ((void)0)
#endif
File Structure Template
// mylib.h - Single-header library template
/*
* MYLIB - Brief description
*
* Usage:
* In ONE source file, define MYLIB_IMPLEMENTATION before including:
* #define MYLIB_IMPLEMENTATION
* #include "mylib.h"
*
* In other files, just include:
* #include "mylib.h"
*
* Configuration:
* MYLIB_MALLOC - Custom malloc (default: malloc)
* MYLIB_FREE - Custom free (default: free)
* MYLIB_ASSERT - Custom assert (default: assert)
* MYLIB_PREFIX - Symbol prefix (default: mylib_)
* MYLIB_DEBUG - Enable debug checks
* MYLIB_NO_CPP - Disable C++ wrappers
*/
#ifndef MYLIB_H
#define MYLIB_H
// ==================== CONFIGURATION ====================
#ifndef MYLIB_MALLOC
#include <stdlib.h>
#define MYLIB_MALLOC(size) malloc(size)
#define MYLIB_REALLOC(ptr, size) realloc(ptr, size)
#define MYLIB_FREE(ptr) free(ptr)
#endif
#ifndef MYLIB_ASSERT
#include <assert.h>
#define MYLIB_ASSERT(x) assert(x)
#endif
// ==================== DECLARATIONS ====================
#ifdef __cplusplus
extern "C" {
#endif
// Public API declarations here...
#ifdef __cplusplus
}
#endif
// ==================== IMPLEMENTATION ====================
#ifdef MYLIB_IMPLEMENTATION
// Internal implementation here...
#endif // MYLIB_IMPLEMENTATION
#endif // MYLIB_H
Quick Reference
// User's single file
#define MYLIB_IMPLEMENTATION
#include "mylib.h"
// Custom allocator
#define MYLIB_MALLOC(size) my_alloc(size)
#define MYLIB_IMPLEMENTATION
#include "mylib.h"
// Dynamic arrays
int *arr = NULL;
arrput(arr, 42);
printf("len=%zu\n", arrlen(arr));
arrfree(arr);