Search code examples
cstructincludecircular-dependencycircular-reference

How to resolve circular struct dependencies in C


So I have two structs, which for simplicity we shall call A and B. A contains a pointer to B, and B contains an A. So here is the code:

a.h

#ifndef A_H
#define A_H

#include "b.h"

typedef struct _A {
    B *b;
} A;

#endif

b.h

#ifndef B_H
#define B_H

#include "a.h"

typedef struct _B {
    A a;
} B;

#endif

Now the issue is that when I import a.h from my main c file, I get errors about how A is an unknown type from b.h. I'm not sure how to resolve this.


Solution

  • The way to do this is to pre-define the structs using empty definition

    typedef struct _A A;
    typedef struct _B B;
    
    typedef struct _A {
        B *b;
    } A;
    
    typedef struct _B {
        A a;
    } B;
    

    You can put the pre-definitions in a global include file to include from wherever you need.

    `