You create the notifier pattern in C by giving the notifier a registry of callback function pointers that subscribers add at runtime, then firing every registered callback whenever an event occurs. That assumes the notifier owns no per-subscriber knowledge beyond a function pointer and a void context pointer, because without the context argument each callback has no way to reach its own state.

That is the whole mechanical core, and it fits in well under a hundred lines. The hard part is everything around it: making removal safe while a notification is in flight, passing typed data through an untyped interface, choosing between one global notifier and many instances, and avoiding dangling pointers when a subscriber's lifetime ends before the notifier's. This guide builds a complete version step by step, then shows where simple implementations break.

The notifier pattern is the C expression of what object-oriented programmers call the observer pattern. The names differ mostly by lineage: embedded and systems code tends to say notifier because the API reads like extending the implementation's own signal, while application code says observer because it reads like an object subscribing to a subject. The mechanics are identical — an event source keeps a list of interested parties and invokes them on change. C has no classes, interfaces, or virtual dispatch, so the pattern gets translated into function pointers, opaque context pointers, and manual lifetime management.

Prerequisites: What You Need Before Writing the Notifier

You need a C99 compiler or newer, since the example uses designated initializers and <stdint.h>-style thinking even where it does not include the header. C89 works if you drop the designated initializers. You also need two design decisions settled first, because they shape the API:

Define the event shape. A notifier can pass nothing (a bare "something changed" ping), a single integer code, or a pointer to a typed payload. Passing nothing is easiest and pushes all data retrieval onto the subscriber, which then needs access to the source. Passing a payload pointer is the most flexible, with the contract that the notifier lends the data for the duration of the call and the subscriber must not retain it.

Decide who is responsible for lifetime. Either the notifier owns the subscription entirely (the subscriber calls an unsubscribe function before it dies), or subscriptions are strictly scoped to a region so they cannot outlive anything. The first is simpler; the second prevents a whole class of bugs. Pick one and document it, because mixing the two conventions is where crashes come from.

Finally, decide whether you need one notifier or many. A single global notifier serving an entire firmware image is common and fine for low counts. Many instances — one per socket, per sensor, per connection — are required as soon as you need independent subscriber sets. The implementation below supports both: the struct is instanceable, and a file-static instance wrapped in functions reproduces the singleton style on demand.

With those settled, the build below is a linear sequence. Each step compiles on its own, so you can stop after step 4 with a working notifier and layer the rest on when you need it.

Step 1: Define the Callback Type and the Contract

The callback signature is the pattern's foundation; changing it later means touching every subscriber, so get it right once.

The context is the subscriber's own pointer, stored at subscription time and handed back on every call. That is what makes the void-pointer interface usable: a subscriber with instance state stores a pointer to its own struct there and casts it back inside the callback. The payload is event-specific and owned by the notifier for the duration of the call only; a subscriber that needs the data later must copy it.

Write that contract in comments above the typedef, because the compiler will not enforce it. In particular, state that the notifier never frees context, never assumes it is non-null without documenting the choice, and never calls a subscriber that has unregistered. These three sentences save more debugging time than any amount of clever code.

One design alternative worth knowing: some implementations pass a notify_event_t and a typed union rather than a void pointer, trading flexibility for type safety. A union works if every event in the system is known up front, which is often true in firmware. The void pointer wins when multiple notifier instances carry different payload types and the code would otherwise need a union covering every possibility. Use whichever the event set actually justifies; do not add a union of forty irrelevant members to avoid one cast.

Finally, define who is allowed to subscribe and unsubscribe during a notification. The answer should be "yes, both are allowed," because subscribers commonly unregister from inside their own callback when they reach a terminal state. Step 4 makes that safe. Do not assume it is safe.

Step 2: Build the Registry Struct

The notifier needs an array of entries, a count, and a capacity. Fixed capacity is the right default in embedded and most systems code because it makes failure predictable and allocation-free; a dynamically grown array is a small variation shown later.

The active flag instead of compaction-on-removal is deliberate. Removing an entry by shifting the array down is cheap and tempting, but it invalidates every index held by an in-progress dispatch loop, which turns a simple callback into a use-after-free or a skipped subscriber. Leaving a tombstone and reusing the slot on the next subscribe is a few wasted bytes in exchange for a stable loop, and count here means "slots occupied by active subscribers" so capacity checks stay honest:

If you would rather compact, do it only at safe points — after a dispatch completes, never inside one — and treat it as an internal housekeeping step. For most systems the tombstones are not worth optimizing away.

The struct is now the entire state of the notifier. An instance is created with notifier_init, usually by the code that owns the event source. There is no construction-time allocation and nothing to free; that is part of the pattern's appeal in constrained environments.

Step 3: Implement Subscribe with Exact-Duplicate Suppression

The duplicate check compares both the function pointer and the context, not just the function. One callback function can legitimately serve many subscribers, each with a different context — for example, a single on_sensor_change handler used per sensor struct. Rejecting duplicates on function alone would break that common case. Rejecting exact pairs prevents the equally common bug where a subscriber registers twice, gets called twice per event, and mysteriously doubles its side effects.

The status return is the success/failure check for this step. Success is NOTIFY_OK, and the slot count increments by exactly one. A duplicate returns NOTIFY_ERR_DUPLICATE with no state change. A full registry returns NOTIFY_ERR_FULL, and the caller must decide whether to treat that as fatal, log it, or grow capacity. Never silently ignore the return in a system where too few subscribers means wrong behavior; treat full as a configuration error.

Step 4: Implement Unsubscribe and Make It Dispatch-Safe

The simplest removal sets active = 0, and that alone is safe during normal operation because never do subscribers hold indices — they hold nothing, and the notifier finds them by scanning the pair. But removal during an in-progress dispatch has a subtle hazard: an entry removed earlier in the current sweep and reused by a new subscribe later in the same sweep could be visited twice. Two mechanisms close that hole.

First, mark any entry touched during a dispatch as deferred:

Second, find_free_slot must only accept entries whose active is exactly 0, never 2, so a pending-removal slot cannot be reused until the current dispatch ends. And the dispatch loop must skip anything that is not active == 1.

That combination eliminates both double-calls and stale reuse. The cost is one extra state value and a small cleanup at the end of the dispatch. The alternative — allow removal only outside dispatch — is simpler but forces subscribers to defer their own removal, which is awkward and routinely forgotten. Since unsubscribing from your own callback is a normal pattern, safe reentrancy is worth the extra branch.

The success check is again the return value: NOTIFY_OK when an active or pending entry was found, NOTIFY_ERR_INVALID otherwise. Not-found is not necessarily a bug — defensive unsubscribe tolerates it — but log it during development, because it usually means the subscriber and notifier disagree about subscription state.

Step 5: Implement Dispatch and the Payload Contract

The local copies of f and ctx before calling matter: a callback is allowed to unsubscribe itself, and after notifier_unsubscribe returns, the entry's fields are in a removal state. Copying first means the call proceeds with stable values regardless. The dispatching counter supports nesting — a callback that raises a second event bumps it to 2, and deferred removals are only flushed when the outermost dispatch ends, which keeps all live loop frames consistent.

Success means every subscriber active at the moment its slot was reached received exactly one call per notify. There is no return value because a notification has no single outcome; if subscribers need to report errors, pass a mutable event struct and let them write into it, or use a separate return-accumulating variant with an explicit "stop on first error" flag documented in the contract.

Reentrancy has one more boundary worth stating: the notifier itself is not thread-safe. If one thread subscribes while another dispatches, mutations race on the entry array. Two threads both calling notifier_notify similarly double-flush the pending list. If your system uses the notifier from interrupts or multiple tasks, wrap the three public entry points in the same protection the rest of the code uses — a critical section, a mutex, or a deferred-work queue — and do not call user callbacks with that protection held, because callbacks may block or take other locks.

Step 6: Register Real Subscribers and Check the Result

A short program proves the whole arrangement works; compile it and count the printed lines.

(The owner back-pointer is a small addition to listener_t; notifier_subscribe on the owning notifier is called with the struct pointer as context.) Main then initializes the notifier, subscribes two listeners and one duplicate, asserts the duplicate returns NOTIFY_ERR_DUPLICATE, fires three events, and checks that each listener's count is exactly 3 and the self-removing listener stopped after two. If the output order is subscriber-insertion order and the duplicate produced no extra line, the core is correct. Then, as a deliberate failure test, unsubscribe a listener from inside its callback and fire again — the removed listener must produce no output, and no crash must occur on the next dispatch.

Two sanity checks on the API itself before moving on: the compile test confirms notifier_subscribe and notifier_unsubscribe reject null functions and null notifiers with NOTIFY_ERR_INVALID, and a registry filled to NOTIFY_MAX_SUBSCRIBERS returns NOTIFY_ERR_FULL on the next subscribe without corrupting counts. Both take a minute and cover the two calling mistakes that remain common even after the dispatch logic is right.

Passing Typed Data Without Losing Type Safety

The void pointer is the pattern's weak spot. The notifier cannot check that a subscriber casts the payload to the right type, and a mismatch is undefined behavior that often looks like a memory corruption bug far from the cause. Three conventions keep this manageable.

Pass the address of a struct that lives for the call. A stack variable declared in the notifying function is the common case, because the notifier calls subscribers synchronously before returning. State in the contract that the pointer is borrowed, document that subscribers must not store it, and prove it in review.

Include the event identity as the first member of any payload struct, so a defensive subscriber can at least assert. It does not type-check, but it catches the "wired the wrong event" mistake at runtime, which is the mismatch that actually happens.

For systems where every payload is known, use a union carrying the event tag. That gives the compiler enough information to enforce the pairing in a switch, and it eliminates the cast entirely. This is the better default when the event set is small and stable; reserve the void pointer for notifiers whose payloads are genuinely open-ended or whose subscribers live in different modules that share no header defining the payload type. In that second case, the header defining notify_fn is also where the payload types for each event are documented, and that documentation is part of the interface.

Breaking the Circular Dependency Between Modules

The largest mechanical problem in real C code is not the dispatch loop but the include graph. Module A raises events, Module B subscribes, and B needs both the callback type and the event type — so if A's header defines them, B includes A, and A already includes B's header for other reasons, you get the classic header cycle. The notifier pattern resolves this by making the interface header independent of the producer.

Create a small notifier.h that defines only notify_event_t, notify_fn, the status enum, the opaque struct forward declaration (or the full struct if it must be instanceable — then place the array size macro here), and the four declared functions. Both the producer and every subscriber include this header. The producer's header then needs no knowledge of subscribers, and the subscriber's header needs no knowledge of the producer's internal types. If a payload struct is needed, define it in a third header that both include.

This split is why the notifier pattern is worth its stub count: it inverts a dependency that would otherwise be bidirectional, at the cost of one type declaring what a signal looks like. If you find yourself passing a pointer to the producer's main struct as the payload, stop and ask whether that struct should be visible to subscribers at all — usually a small event-specific struct is the more honest interface and keeps subscribers from reaching into the producer.

When Notifiers Work, and When They Fight You

The pattern is the right answer when events are rare, subscribers need to know that something happened rather than follow a stream, and failure to deliver must not be visible to the producer. Configuration changes, record add/remove, connection state transitions, and settings resets all fit. So does the simplest use case: one component that wants to be told when a shared chunk of state is ready, without polling it.

It becomes the wrong answer in three common situations. If events fire in tight loops at high frequency, a linear scan of sixteen callbacks per event is cheap in isolation but the total adds up, and the untyped indirection prevents inlining; at that point a direct function call or a typed stream interface with buffered delivery is usually better. If the event set is entirely known and static forever, hand-written direct calls achieve the same coupling with no registration machinery. If subscribers need delivery guarantees — every event, in order, even if the subscriber is slow — the pattern as written has no queue, and adding one changes its character into a message bus with all the backpressure questions that follow. Recognizing that transition early is cheaper than growing the notifier into one byte at a time.

The pattern also carries costs that are easy to underestimate: the void pointer contract, the reentrancy rules around dispatch, the fact that there is no built-in way to know whether a notification was handled, and diagnosability problems when a chain of callbacks hides which subscriber misbehaved. Mitigating the last one usually means an optional tracing hook, or temporary instrumentation at each call site, which is fine but should be planned rather than improvised.

Variations Worth Knowing

Three variants cover most real-world shifts without rewriting the API. If subscriber count is unknown, replace the fixed array with notify_sub_t *subs; size_t cap, count; and grow by doubling on subscribe, freeing in the notifier's destroy function. The dispatch logic is unchanged; only capacity management and lifetime discipline are new. If subscribers should be prioritized, keep an integer priority per entry and keep the array sorted by insertion order — no, by priority, stable within equal priorities — so dispatch order is deterministic; the pattern makes no promise about order unless you document one, and the sorted insertion is the smallest way to promise it.

If delivery must be deferred, keep a tiny ring buffer of events inside the notifier and deliver on a tick or on an explicit notifier_pump call rather than calling back from the producer's stack frame. This decouples timing but introduces overflow policy (drop newest, drop oldest, coalesce), which is a decision with real user-visible consequences and belongs in the contract. A third variation, filtering by event, stores a bitmask per subscriber and skips callbacks not interested in the current event; that is useful only if every event would otherwise cause many no-op calls, which is measurable rather than assumed.

Each variation alters exactly one concern. Resist combining them before one is demonstrably needed; the unmodified fixed-array version has been adequate for far more systems than the more elaborate bus designs replace.

Checking Your Implementation Against the Contract

A finished notifier passes a short checklist. Registration returns exact statuses and duplicate pairs are rejected without side effects. Dispatch calls every active subscriber once, in insertion order, with the context surviving the call. Self-unsubscribe from within a callback works and the removed subscriber receives no further events. Unsubscribe-and-resubscribe during a dispatch delivers exactly one call to the callback, not two. Filling capacity and attempting one more subscribe returns full with the count unchanged. And null arguments to every public function produce the invalid status rather than a crash.

Run those checks in a test program with printed counters, not by inspection; the duplicate-delivery case in particular is nearly invisible by reading and obvious by counting. After they pass, the implementation is at the size most projects need indefinitely. The next feature worth adding is a destroy function that scans for any remaining active subscriber and either assert-fails in debug builds or logs in release, so a leaked subscription surfaces at teardown instead of as a mysterious later callback into freed memory.