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 1h ago
Oh well the implementation itself is in the C file, I just trimmed the fat when posting.
The problem still remains because I can't access the struct observer fields in the C file either if I forward declare it