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
Show parent comment
1
u/Zeta_ggwp 54m ago
I did think about this. I was trying to make it so observer keeps the systems inside so it can be a stack variable. But I guess in hindsight it doesn't make much sense to have things like an audiosystem be so deeply tied to the observer object it is contained in.
Is the union still worth keeping if I have a pointer or would it be better to change it to a simple void pointer instead? Since the type enum is already there.