如何在C中声明从属结构?

如何在C中声明从属结构?,c,C,我需要声明一个两者都使用的结构。 例如,我如何编译它 z3 src # cat dependant.h typedef struct egg_t egg_t; typedef struct chicken_t chicken_t; typedef struct egg_t { int egg_num; struct chicken_t chicken; } egg_t; ty

我需要声明一个两者都使用的结构。 例如,我如何编译它

z3 src # cat dependant.h
typedef struct egg_t egg_t;
typedef struct chicken_t chicken_t;

typedef struct egg_t {
        int                             egg_num;
        struct chicken_t                chicken;
} egg_t;

typedef struct chicken_t {
        int                     chicken_num;
        struct egg_t                    egg;
} chicken_t;
z3 src # gcc -c dependant.h
dependant.h:6:20: error: field 'chicken' has incomplete type
dependant.h:7:3: error: redefinition of typedef 'egg_t'
dependant.h:1:22: note: previous declaration of 'egg_t' was here
dependant.h:12:3: error: redefinition of typedef 'chicken_t'
dependant.h:2:26: note: previous declaration of 'chicken_t' was here
z3 src #

您可以创建指向不完整类型的指针(取消TypeDef,因为它们不添加任何内容):


当然,正确的答案是首先避免这种循环依赖,但这并不总是可能的

想想看;
sizeof(egg\t)
是什么?一旦你有了指针,
\u t
后缀并没有特别的帮助,特别是因为标记名总是跟在
struct
关键字后面。
struct egg_t;
struct chicken_t;

struct egg_t {
  int egg_num;
  struct chicken_t *chicken;
};

struct chicken_t {
  int chicken_num;
  struct egg_t *egg;
};