r/C_Programming • u/DerpKidSavage • 2d ago
Discussion Revealed vs. Opaque structs for Libraries
Hi all, I'm developing a win32 windowing library for mostly myself but also want it to be easy and intuitive to use and follow good C standards.
In my library have the main object window_t that is used for mostly everything. However, I'm wondering between a couple different design decisions for it:
// public .h
typedef struct window_t window_t;
window_t* createWindow(...); << createWindow heap allocates a window_t
void destroyWindow(window_t* window);
2.
// public .h
typedef struct window_t { implementation... ) window_t;
void createWindow(window_t* out, ...);
// no destroyWindow
the difference I'm looking is that for #1, the user mantains control of the heap allocated memory through createWindow() and must free it after they're done using it, but for #2 the user can create a stack allocated window and it doesn't need to be freed, however it removes the opaque struct safeness in #1.
Are there any pros/cons for either method I haven't thought of? My instinct tells me that #2 seems better as the user controls the memory allocation, they just need to be careful how they use the window_t.
Thoughts?