簡體   English   中英

在另一個typedef結構中使用的typedef結構的前向聲明

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM