Skip to content
systemcoding.dev
Toolchains

Design a Stable C ABI for a Shared Library

Keep a shared library's C interface stable across releases with opaque handles, size-tagged structs, explicit error codes and a versioned symbol set.

7 min read
Summarize in AI
Flat illustration of an assembly listing with addresses and mnemonics, with the C, GNU and Arm logos.

A shared library can promise its users that a program built last year will work with the library you ship today. The promise has a name, the application binary interface, and it is easy to break without noticing. The compiler does not warn when a structure grows, an enum gains a value in the middle, or a function changes the meaning of an argument. The program still loads, because the soname matches, and then misbehaves. This post gives the rules that keep a C interface stable, shows each with a failing and a fixed version, and ends with the checks that catch a break before a release. It uses GCC 14 and glibc 2.39 on Linux x86-64. The naming side of versioning is in versioning a shared library with -Wl,-soname.

What the ABI includes

The API is what the source code looks like: function names, argument types. The ABI is what the compiled code depends on: symbol names, the size and layout of structures, the values of constants, the calling convention, and the meaning of every argument. Two libraries with the same API can have different ABIs. A caller compiled against the old header has the old sizes and offsets baked into its machine code, and no later check can fix it.

Rule one: hide your structures

The most common break is a public structure that grows. Suppose the library exposes a configuration struct and callers allocate it:

config_v1.hc
struct vec_config {
    int threads;
    int block_size;
};

int vec_init(struct vec_config *cfg);

A caller declares struct vec_config cfg; on its stack, and its code reserves eight bytes. Release 1.1 adds a field:

config_v2.hc
struct vec_config {
    int threads;
    int block_size;
    int use_simd;
};

The old caller still reserves eight bytes. vec_init now writes twelve, corrupting whatever lies next to the structure on the stack. Nothing fails at load time. The fix is an opaque handle: the header declares the type without defining it, and the library allocates it.

vec.hc
typedef struct vec_ctx vec_ctx;

vec_ctx *vec_create(void);
void vec_set_threads(vec_ctx *ctx, int threads);
int vec_get_threads(const vec_ctx *ctx);
void vec_destroy(vec_ctx *ctx);

Callers can only hold a pointer, so the library is free to change the structure's contents and size. The price is accessor functions for every field. Where the structure must be public, because the caller fills it in and the library reads it, add a size field at the start so the library can tell which version it received:

vec.hc
struct vec_options {
    size_t size;      /* caller sets to sizeof(struct vec_options) */
    int threads;
    int block_size;
};

int vec_run(const struct vec_options *opts);
vec.cc
#include <stddef.h>
#include "vec.h"

#define HAS_FIELD(p, f) ((p)->size >= offsetof(__typeof__(*(p)), f) + sizeof((p)->f))

int vec_run(const struct vec_options *opts)
{
    int threads = HAS_FIELD(opts, threads) ? opts->threads : 1;
    int block   = HAS_FIELD(opts, block_size) ? opts->block_size : 64;
    return threads * block;
}

A new library appends fields at the end only, and reads a field only when the caller's size covers it. An old caller passes a smaller size, so the library uses a default for the new field. Windows and Vulkan use this pattern. Never reorder or remove fields, and never insert one in the middle.

Rule two: enums and constants are part of the contract

Values must never change meaning. Add new enum members at the end, and give them explicit numbers so a reordering cannot shift the others:

vec.hc
enum vec_mode {
    VEC_MODE_FAST = 0,
    VEC_MODE_EXACT = 1,
    VEC_MODE_COMPAT = 2   /* added in 1.2 */
};

If a function takes an enum and a new library returns a value an old caller does not know, the caller's switch has no case for it. Document that callers must handle unknown values with a default branch. The underlying type of an enum is also an ABI detail, since sizeof(enum vec_mode) is implementation-defined. When a structure holds one, use a fixed-width integer in the structure and an enum in the function arguments.

Rule three: errors are values, not exceptions

C++ exceptions crossing a library boundary are an ABI hazard, since a caller built with another compiler or runtime cannot catch them. A stable C interface returns an error code and writes results through pointers:

vec.hc
typedef enum {
    VEC_OK = 0,
    VEC_ERR_NOMEM = -1,
    VEC_ERR_INVALID = -2
} vec_status;

vec_status vec_dot(const double *a, const double *b, int n, double *out);

Return an integer status, never a bool or a type that might change width, and reserve negative values for errors so new codes can be added. Keep global errno-style state out of the interface, because it breaks with threads and with different runtimes.

Rule four: export only what you mean to

Every global symbol a shared library exports is part of its ABI. A helper that you meant to be private but did not hide becomes something a user can depend on, and removing it later breaks them. Compile with -fvisibility=hidden and mark the public functions explicitly:

vec_export.hc
#define VEC_API __attribute__((visibility("default")))
vec.cc
#include "vec_export.h"

VEC_API vec_status vec_dot(const double *a, const double *b, int n, double *out);

Verify the exported set with nm -D --defined-only libvec.so.1. The list must match the header. A hidden-by-default build is the best protection, as explained in controlling symbol visibility with -fvisibility=hidden.

Rule five: do not pass types you do not control

Passing FILE *, std::string, std::vector or a type from a third-party library across the boundary ties your ABI to theirs. A FILE * from one C library is not usable by another. A std::string changed layout between the old and new GCC library ABIs. Use plain types: pointers to bytes with a length, integers of fixed width, and C strings. Prefer int32_t and uint64_t over long, which is 8 bytes on Linux x86-64 and 4 on Windows.

Rule six: allocate and free on the same side

A buffer allocated by the library with malloc and freed by the caller with free works only when both use the same allocator. Two different runtimes, or a debug and release build of the same one, do not. Provide vec_free(void *p) and document that the library frees what the library allocates:

vec.hc
char *vec_describe(const vec_ctx *ctx);   /* caller must pass to vec_free */
void vec_free(void *p);

Checking for a break

Rules help, and a tool checks them. abidiff from libabigail compares two builds of a library, with the headers, and reports removed symbols, changed signatures and layout changes:

Shell
abidiff --headers-dir1 old/include --headers-dir2 new/include \
        old/libvec.so.1.0.0 new/libvec.so.1.1.0
Text
Functions changes summary: 0 Removed, 1 Changed, 1 Added function
Variables changes summary: 0 Removed, 0 Changed, 0 Added variable

1 function with some indirect sub-type change:

  [C] 'function vec_status vec_run(const vec_options*)' has some indirect sub-type changes:
    parameter 1 of type 'const vec_options*' has sub-type changes:
      in pointed to type 'const struct vec_options':
        type size changed from 96 to 128 (in bits)
        1 data member insertion:
          'int use_simd', at offset 96 (in bits)

The report flags a structure growth at the end, which is allowed here only because of the size-tagged design. The exact text depends on the libabigail version, and the numbers are an example. Run it in CI between the last release and the build under test, and fail on removed functions or changed existing offsets. Pair it with a header check that no public struct appears without a leading size field.

A short review checklist

Before every release, walk the public header with these questions. Does any public struct lack a leading size, and could a caller allocate it? Did any enum value move or change meaning? Does any function now return a value the old version never returned? Is each exported symbol in the header, and each header function exported on purpose? Did a type from another library, or from the C++ standard library, slip into a signature? A yes to the first, third or fifth question is a major version bump, and a no to every question means the minor number is enough.

Write the answers into the release notes. A reader who sees "ABI: compatible, one function added" knows they can upgrade with no rebuild, and a reader who sees "ABI: soname bumped, structure vec_options changed" knows to plan one. That small sentence saves more support time than any other line in a release announcement.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.