Opaque Types
An opaque type is a struct whose members are not visible in the header. Callers hold a pointer and call functions. Only the implementing .c file knows the layout.
Detailed Explanation
Encapsulation in C is a header trick. The header declares
typedef struct Counter Counter;
Counter *counter_new(void);
void counter_free(Counter *c);
void counter_bump(Counter *c);
int counter_get(const Counter *c);
struct Counter is incomplete in every file that only includes the header. You cannot declare Counter c; on the stack. You cannot take sizeof(Counter). You cannot read c->value. You can pass Counter * around, store it, and hand it to the functions. The defining .c includes a private header or defines struct Counter { ... }; before the functions, and there the type is complete.
This is how FILE works. It is how you keep a library ABI stable when the internals grow a field. It is how you stop callers from depending on a lock, a buffer, or a version tag you need to change later.
The cost is allocation. Because the caller cannot see the size, the library must allocate. counter_new calls malloc. counter_free calls free. Callers cannot embed a Counter inside their own struct; they embed a Counter *. That extra indirection is real, and it is the usual trade for a stable, hideable layout.
A lighter variant exposes the size without exposing the members: the header says struct Counter; and enum { COUNTER_SIZE = 32 };, and the caller provides aligned storage. This is brittle — the size must stay accurate — and rare outside embedded code that cannot malloc. Prefer a heap object unless you have a measured reason.
Opacity is not security. A caller who casts the pointer and guesses the layout can still read the fields. It is a compiler-enforced API boundary, which is what most programs actually need.
Code Examples
/* counter.h — callers see this */
#ifndef COUNTER_H
#define COUNTER_H
typedef struct Counter Counter;
Counter *counter_new(int start);
void counter_free(Counter *c);
void counter_bump(Counter *c);
int counter_get(const Counter *c);
#endif/* counter.c — layout is private to this file */
#include "counter.h"
#include <stdlib.h>
struct Counter {
int value;
};
Counter *counter_new(int start)
{
Counter *c = malloc(sizeof *c);
if (c == NULL) {
return NULL;
}
c->value = start;
return c;
}
void counter_free(Counter *c)
{
free(c);
}
void counter_bump(Counter *c)
{
if (c != NULL) {
c->value += 1;
}
}
int counter_get(const Counter *c)
{
return (c == NULL) ? 0 : c->value;
}Common Gotchas
`Counter c;` is a constraint violation while the type is incomplete
callers must use `Counter *` and the constructor.
Every `new` needs a `free`
the library owns the allocation. Leaking the pointer leaks the object, and freeing it twice is a double-free.
Two translation units that both define `struct Counter` with different members, then pass the pointer across, are on their own
one definition rule still applies at the ABI level. Keep a single implementing file.