r/C_Programming • • 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; 
};
1 Upvotes

9 comments sorted by

View all comments

Show parent comment

1

u/lfdfq 1h ago

You don't have to include event.h in stats.h just to declare the prototype of the function that takes a pointer to a struct Observer. The following is totally valid:

struct C;
void foo(struct C *p);

the type struct C is incomplete until it is defined, and thus doesn't have a size or fields yet, but you can still use it in declarations of other types that don't need either of those things. Then you can include stats.h in event.h without there being a cycle.

You can then just include both event.h and stats.h in stats.c, if you need both sets of types. That's also fine.

1

u/Zeta_ggwp 1h ago edited 1h ago

Ok that's a good solution. Thank you.

I'll use a pointer to stats inside observer instead tho because I feel it conveys the meaning better to keep all the code related to each system separate.