• Use structs as local namespaces in C code

struct Engine_Data {
    struct State* currentState;
    int someFlags;
};

static struct Engine_Data s;

$[Get Code]1

Putting all static vars in a compilation unit into a single struct has advantages:

  • Watching in a debugger is easy since there's a single state variable containing all state
  • Transition from static to reusable objects is much easier since instance data is already encapsulated

struct Engine_vtable {
    int (start)();
    int (
stop)();
};

/* Reusable class /
struct Engine {
    struct Engine_vtable
vtable;
    struct Engine_Data s;
};

/* Initializer /
void Engine_Init(struct Engine
e);

int main()
{
    struct Engine engine;

    Engine_Init(&engine);
}

$[Get Code]2