0 day streak
c / expert
Snippet

Encapsulation via Opaque Pointers

Opaque pointers (or 'PIMPL' in C) hide the implementation details of a struct from the user. By only providing a forward declaration in the header, the compiler prevents users from accessing internal fields or assuming the struct's size, ensuring a stable binary interface (ABI).

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// In public header: session.h
typedef struct Session Session;
Session* session_create(int id);
void session_destroy(Session* s);
// In private implementation: session.c
#include <stdlib.h>
struct Session {
int id;
char internal_key[32];
};
Session* session_create(int id) {
Session* s = malloc(sizeof(struct Session));
if (s) s->id = id;
return s;
}
void session_destroy(Session* s) { free(s); }
Breakdown
1
typedef struct Session Session;
Creates an alias for an incomplete struct type, usable only via pointers in external code.
2
struct Session { ... };
The full definition is hidden in the .c file, preventing direct access to 'internal_key' by library users.
3
Session* s = malloc(sizeof(struct Session));
The library manages memory allocation because only the library knows the actual size of the struct.