简体   繁体   中英

how to declare dependant structs in C?

I need to declare a struct that both use one another. For, example, how do I compile this?

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 #

You can create pointers to incomplete types (nixing the typedefs since they don't add anything):

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;
};

Of course, the right answer is to avoid this kind of circular dependency in the first place, but that's not always possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM