[英]Forward declaration of typedef struct used in another typedef struct
我想转发声明一个typedef结构,在另一个结构中使用它,然后实现原始结构。
我尝试了以下代码,但未编译。
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;
};
任何想法?
您只能向前声明类型的存在,然后使用指向它的指针。 这是因为指针的大小始终是已知的,而前向声明的compund类型的大小尚不清楚。
struct s1;
struct s2;
struct big_struct {
struct s1* pmy_s1;
struct s2* pmy_s2;
};
struct s1 {
int i1;
};
struct s2{
int i2;
};
注意,由于我的背景,我习惯于编写极其向后兼容的代码。
乔纳森·莱夫勒(Jonathan Leffler)提供了有关C标准更现代版本中是否需要/不需要的信息。 请参阅下面的评论。
如果您真的被迫执行该命令(我不在乎为什么),那么我想到要进行编译的一件事就是通过使struct _big_struct
指针:
typedef struct s1 s1;
typedef struct s2 s2;
typedef struct _big_struct {
s1 *my_s1;
s2 *my_s2;
} big_struct;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.