[英]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.