r/C_Programming • u/Zeta_ggwp • 40m 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;
};
3
u/lfdfq 36m ago edited 26m ago
Why does the statsOnNotify function definition need to be in the header file? The function declaration should be fine, you can forward declare struct types when used as pointers, you just can't have the implementation there, too.
EDIT: the EventType enumeration cannot be forward declared however, so that would probably have to move into stats.h or into a third file e.g. event_types.h
1
u/WittyStick 25m 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.