liveBook · Manning

Opaque object

As explained in Modern C, Third Edition

An opaque structure is a C structure type whose complete member definition is hidden from code that uses its interface.

An opaque structure is a C structure type whose member definition remains hidden from code using its interface. Client code can declare and pass pointers to the type without knowing its layout. section 11.2

Forward-declared library type

A header can expose the type and its operations without defining its members: struct toto; struct toto* toto_get(void); void toto_destroy(struct toto*); void toto_doit(struct toto*, unsigned); Client code can obtain, destroy, and operate on a toto object through its pointer. The implementation translation unit supplies the hidden structure definition. section 11.2

The interface relies on these rules:

  • Uses pointers to an incompletely known structure type; the structure definition itself need not be visible to the client or compiler using the interface. section 11.2
  • Separates library interface from implementation while allowing functions to return and accept pointers to the hidden object. section 11.2
  • Keeps null-pointer handling visible when the interface writes pointer types explicitly; hiding pointers inside a typedef can conceal that special value. section 11.2
/* forward declaration of struct toto */
struct toto;
struct toto* toto_get(void);
void toto_destroy(struct toto*);
void toto_doit(struct toto*, unsigned);

Browse the minimal forward declaration and function declarations for an opaque structure interface. section 11.2

How Modern C, Third Edition covers it

How deep it goes
Defines forward declarations, pointer use, representation rationale, and typedef visibility, but not the hidden structure's members.
Examples
Uses a forward-declared struct toto with get, destroy, and operation functions, plus pointer typedef alternatives.
What it assumes
Assumes familiarity with C structures, pointers, function declarations, and typedefs.
What you can do after
Builds a client-facing C interface around a structure whose definition remains private to its implementation.
How it connects
Connects incomplete structure types, pointers, forward declarations, null pointers, typedefs, and library interfaces.

Also explained in

Compare how 2 books explain opaque object →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.