r/cprogramming • • 1d ago

Revealed vs. Opaque structs for Libraries

/r/C_Programming/comments/1y5i6p2/revealed_vs_opaque_structs_for_libraries/
2 Upvotes

2 comments sorted by

1

u/zhivago 1d ago

It just doesn't matter.

If someone wants to they can just provide their own definition of the struct.

You can get precisely the same level of security by documentation.

A comment saying that something is for internal use is enough.

When code breaks due to depending on something clearly unstable the author can't complain.

1

u/Dapper-Situation-864 1d ago

Both work, but a few things tip it for a library:

  • ABI stability. With #2 the struct layout is part of your public ABI. Add a field later and anything compiled against the old header has the wrong sizeof. If you ever ship it as a DLL, that bites. With #1 you can change the internals freely.
  • Win32 specifics. A window is tied to an HWND, and your WndProc usually gets the pointer back via SetWindowLongPtr(GWLP_USERDATA). If the user puts window_t on the stack and it goes out of scope, or they copy it by value, while the HWND is still alive, the WndProc is holding a dangling pointer. That alone pushes me toward #1, or at least toward documenting that a window_t must never be moved or copied.
  • "No destroyWindow" isn't really true for #2. You still own an HWND, maybe a registered class, DCs/GDI objects. The user needs a cleanup call either way; stack allocation only saves the free().
  • You can keep it opaque and still give the caller control of memory: take an optional allocator callback in a config struct, or expose something like size_t window_size(void); plus int window_init(void *mem, ...) so they can place it wherever they like.

Personally I'd go opaque here. Windows are few and long-lived, so the heap allocation cost is irrelevant, and you keep the freedom to change the struct without breaking users.