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?
This will cut it in C:
You can rearrange
B
andA
as desired.Google C/C++ guidelines suggests:
That'd mean:
a.h contents:
b.h contents:
If you prefer something a bit safer (but longer to compile) you can do this:
a.h contents:
b.h contents:
You pre-define the struct only, in that way you can still declare a pointer:
In
a.h
:Note how I use separate names for the
typedef
and struct tags, to make it a bit clearer.Don't #include a.h and b.h, just forward-declare A and B.
a.h:
b.h:
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 likea->b->a
.