Frontend Labs
⋯

37. uthash and klib: generics via macros

What they are: two of the most-vendored single-header C libraries on GitHub — uthash.h adds a hash table to any existing struct via macros; klib's khash.h/kvec.h do the same for hash tables and vectors with a slightly different macro style. Both solve exactly Section 16.1's "C has no generics" problem, at library scale.

// uthash: turn an existing struct into a hash-table entry by adding ONE field
#include "uthash.h"

typedef struct {
    int id;              // the key
    char name[32];
    UT_hash_handle hh;   // <-- makes this struct hashable; this IS Section 19's
                          //     intrusive-container idea, applied to a hash table
                          //     instead of a linked list
} User;

User *users = NULL;   // the hash table itself is just a NULL pointer to start

void add_user(User *u) { HASH_ADD_INT(users, id, u); }
User *find_user(int id) { User *u; HASH_FIND_INT(users, &id, u); return u; }

UT_hash_handle hh embedded in User is precisely Section 19's container_of technique — uthash.h's macros compute back from hh's address to the owning User*, the exact same trick as the Linux kernel's list_head, just wrapping a hash table's bucket/chain pointers instead of a doubly-linked list's next/prev. Once you've built Section 19's intrusive list by hand, uthash.h's ~1000 lines of macros stop looking like magic and start looking like "the thing I already understand, at production polish level."


Generated from real-life-c-guide.md · 8 Oct 2026 16:36