Tech /

Struct Namespaces





edit SideBar

Struct Namespaces
  • Use structs as local namespaces in C code
struct Engine_Data {
    struct State* currentState;
    int someFlags;
};

static struct Engine_Data s;

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);
}
Recent Changes (All) | Edit SideBar Page last modified on 21 February 2013, at 02:21 PM UTC Edit Page | Page History
Powered by PmWiki