如何处理 typedef 结构中的循环依赖

How to handle circular dependencies in typedef'd structures

我有两个模块,a 和 b。

a.h:

#ifndef A_H_
#define A_H_

#include "b.h"

typedef struct {
    b_t *b;
    ...
} a_t;

#endif // A_H_

b.h:

#ifndef B_H_
#define B_H_

#include "a.h"

typedef struct {
    a_t *a;
    ...
} b_t;

#endif // B_H_

我该如何修改它才能编译? (我想保留两个独立的编译单元。)


编辑:我忘了制作结构成员指针。

[此答案仅适用于原始问题,其中指针用作struct成员]。

你不能。

基本上你有

typedef struct {
    b_t b;
} a_t;
typedef struct {
    a_t a;
} b_t;

并且没有前向声明可以帮助您。这里有一个不可能的结构:sizeof 将是无限的。

使用前向声明:

a.h:

struct b_t;

typedef struct a_t {
  struct b_t *b;
} a_t;

b.h:

struct a_t;

typedef struct b_t {
  struct a_t *a;
} b_t;

这完全不可能。你不能让一个结构成为它自己的成员,甚至不能传递。但是,当您使用指针时,这是可能的。使用结构声明:

typedef struct a_struct *a_t;

typdef struct {
    a_t a;
} *b_t;

typedef struct a_struct {
    b_t b;
} a_t;

[此答案仅适用于原始问题,其中指针未用作结构成员]。

那是不可能的。自然不可能有这样的结构。

假设:

struct a {
    struct b b;
    int i;
};

struct b {
    struct a a;
    int i;
};

您对 sizeof(struct a) 有什么期望?这个结构会爆炸,无法编译。

但是,如果你把它们转为指针,它是可以编译的:

struct a;

struct b {
    struct a *ap;
};

struct a {
    struct b *bp;
};

此代码确实编译:http://ideone.com/GKdUD9