r/C_Programming • u/Zeta_ggwp • 1h ago
Question Need help avoiding circular dependency
[Solved but I'll gladly accept new solutions]
I am making a small clone of asteroids on C and plan to use the observer pattern described in Game Programming Patterns by Bob Nystrom. (Adapted to C) To do so, I currently have 2 files, a stats system (stats.h/c) and the actual observer pattern code (event.h/c). (Relevant Source code below)
My problem is that stats.h/c requires access to structs and enums defined in event.h, but event.h has a struct that contains a union with a struct defined in stats.h, and I don't know how to solve the circular dependency.
stats.h and stats.c (implementation of statsOnNotify lies in C file)
struct Stats { ... };
// statsOnNotify requires struct Observer and enum EventType, defined in event.h
void statsOnNotify(struct Observer \*observer, enum EventType event, void \*data) {
switch (event) {
case ...: {
//Access Observer union to access the struct Stats data
}
break;
}
}event.h
enum EventType { ... };
struct Observer;
// Requires struct Observer and enum EventType.
typedef void (\*NotificationHandler)(struct Observer \*observer, enum EventType event, void \*data);
enum ObserverType { ... };
// struct Observer requires struct Stats, defined in stats.h
struct Observer {
enum ObserverType type;
union {
struct Stats stats;
} data;
NotificationHandler onNotify;
};
View all comments
1
u/WittyStick 1h ago
Because
struct Statsis an incomplete type inevent.h, we can't put it directly into theObservertype - we would have to lift theStatsinto a separate header that bothstats.handevent.hinclude if this were necessary.A common solution here is to give the
Observera pointer toStatsrather than trying to put the stats as a nested structure. We can have a pointer to an incomplete type no problem.