简体   繁体   中英

Forward declaration of typedef struct used in another typedef struct

I would like to forward declare a typedef struct, to use it in another struct, and then to implement the original struct.

I have tried the following code but does not compile.

struct _s1;
struct _s2;

typedef struct _s1 s1;
typedef struct _s2 s2;

typedef struct _big_struct {
    s1 my_s1;
    s2 my_s2;
} big_struct;

struct _s1 {
    int i1;
};

struct _s2{
    int i2;
};

Any idea?

You can only forward declare the existence of a type and then use a pointer to it. This is because the size of a pointer is always known, while the size of a forward declared compund type is not, yet.

struct s1;
struct s2;

struct big_struct {
    struct s1* pmy_s1;
    struct s2* pmy_s2;
};

struct s1 {
    int i1;
};

struct s2{
    int i2;
};

Note, because of my background, I am used to writing extremely backward-compatible code.
Jonathan Leffler has provided information on need/not-need in more modern versions of the C standard. See the comments below.

If you are really forced with that order (I don't care why), one thing that comes in my mind to have it compile is by making the struct _big_struct entries pointers:

typedef struct s1 s1;
typedef struct s2 s2;

typedef struct _big_struct {
    s1 *my_s1;
    s2 *my_s2;
} big_struct;

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