July 14, 2011
•
Typedef / Struct Forward Declaration in Straight C
If I want to create an opaque typedef of a struct called Foo and I want to encapsulate it by only allowing the library user to use the struct according to the functions I provide, without littering their code with 'struct Foo' everywhere? It's a little confusing to set up but easy if you know the formula.
Foo.h:
...
struct FooTag; // "Tag" could be anything
// but the struct and typedef need separate names
typedef struct FooTag Foo;
Foo* Foo_Init(int bar, int baz);
bool Foo_IsReady(int bat, int bash);
...
Foo.c:
struct FooTag
{
... // fill out fields of struct here;
// consumer of Foo.h cannot poke inside Foo structs
int FooMitzvah;
... // etc.
}
Simple to use, confusing the way the pieces come together.