Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C recursive header file inclusion problem?

Suppose you have to related structures defined in 2 header files like below:

a.h contents:

#include b.h

typedef struct A
{
  B *b;
} A;

b.h contents:

#include a.h

typedef struct B
{
  A *a;
} B;

In such this case, this recursive inclusion is a problem, but 2 structures must point to other structure, how to accomplish this?

like image 428
whoi Avatar asked Dec 21 '22 23:12

whoi


1 Answers

Don't #include a.h and b.h, just forward-declare A and B.

a.h:

struct B; //forward declaration
typedef struct A
{
    struct B * b;
} A;

b.h:

struct A; //forward declaration
typedef struct B
{
    struct A * a;
} B;

You might want to think about how tightly coupled the classes are. If they're very tightly coupled, then maybe they belong in the same header.

Note: you'll need to #include both a.h and b.h in the .c files to do things like a->b->a.

like image 197
Doug Avatar answered Jan 07 '23 03:01

Doug