Opaque Type
The opaque-type pattern hides a struct's members behind an incomplete type in the public header. Callers hold a pointer and call functions. The layout can change without breaking their source.
Detailed Explanation
This is the design-pattern name for what the OOP pages call an opaque type. The pattern's job is API stability. You ship typedef struct Logger Logger; and Logger *logger_open(const char *path);. Next year you add a mutex inside struct Logger and the callers do not recompile against a new sizeof, because they never had sizeof.
The implementing translation unit defines the struct. Only that file, or a private header included only there, sees the members. Tests that need to inspect internals either live in that file or include the private header on purpose. Public tests use the public functions.
The pattern forces heap allocation (or a library-owned pool). That is the cost. The benefit is that you can add fields, change a buffer size, or swap a lock type without an ABI break for anyone who only stored Logger *. Changing the function list is still an ABI break.
A weaker form exports the struct but names a field impl that is void *. Callers can still copy the wrapper by value and smash it. Incomplete type is stricter and better.
FILE is the standard library's opaque type. Copying a FILE by value is not allowed and would not work. Your types should feel the same: create, use through functions, destroy.
Code Examples
/* logger.h */
#ifndef LOGGER_H
#define LOGGER_H
typedef struct Logger Logger;
Logger *logger_open(void);
void logger_write(Logger *l, const char *line);
void logger_close(Logger *l);
#endif/* logger.c */
#include "logger.h"
#include <stdio.h>
#include <stdlib.h>
struct Logger {
int lines;
};
Logger *logger_open(void)
{
return calloc(1, sizeof(struct Logger));
}
void logger_write(Logger *l, const char *line)
{
if (l == NULL) {
return;
}
l->lines++;
fputs(line, stdout);
fputc('\n', stdout);
}
void logger_close(Logger *l)
{
free(l);
}Common Gotchas
Defining the struct in the public header ends the opacity
a later field is an ABI break for stack allocation you just invited.
Callers will `free` the pointer if you do not give them `close`
extra allocations inside the object then leak.
Incomplete types cannot be members by value
callers embed `Logger *`.
Two `.c` files defining `struct Logger` differently and passing the pointer is a
Two `.c` files defining `struct Logger` differently and passing the pointer is an ODR-style bug at the ABI level