C recursive header file inclusion problem?

2019-05-05 07:25发布

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?

4条回答
SAY GOODBYE
2楼-- · 2019-05-05 07:52

This will cut it in C:

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

You can rearrange B and A as desired.

查看更多
一纸荒年 Trace。
3楼-- · 2019-05-05 07:58

Google C/C++ guidelines suggests:

Don't use an #include when a forward declaration would suffice

That'd mean:

a.h contents:

typedef struct B B;

typedef struct A
{
  B *b;
} A;

b.h contents:

typedef struct A A;

typedef struct B
{
  A *a;
} B;

If you prefer something a bit safer (but longer to compile) you can do this:

a.h contents:

#pragma once
typedef struct A A;

#include "B.h"

typedef struct A
{
  B *b;
} A;

b.h contents:

#pragma once
typedef struct B B;

#include "A.h"

typedef struct B
{
  A *a;
} B;
查看更多
倾城 Initia
4楼-- · 2019-05-05 08:03

You pre-define the struct only, in that way you can still declare a pointer:

In a.h:

typedef struct B_ B;

typedef struct A_
{
  B *b;
} A;

Note how I use separate names for the typedef and struct tags, to make it a bit clearer.

查看更多
霸刀☆藐视天下
5楼-- · 2019-05-05 08:09

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.

查看更多
登录 后发表回答