[英]how to declare dependant structs in 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;
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 #
您可以创建指向不完整类型的指针(nixing typedef,因为它们不添加任何内容):
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;
};
当然,正确的答案是首先避免这种循环依赖,但这并不总是可行的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.