当定义结构体时,避免"typedef 重新定义"警告

3

我正在定义一些相互引用的结构体,并在使用之前对它们进行了 typedef,以便每个结构体“知道”其他结构体(如果没有这样做,会出现编译错误)。不确定这是否必要或正确。

现在,在使用 gcc 编译时,我收到“typedef 重定义”的警告。应该如何正确处理?

typedef struct a A;
typedef struct b B;
typedef struct c C;

struct a {
    B* list;
    A* parent;
};

struct b {
    A* current;
    B* next;
};

struct c {
    A* current;
    A* root;
};

更新:由于愚蠢的复制粘贴,导致此标题在另一个文件中被重复包含。我对C语言不是很熟悉,以为这与在文件中两次使用结构体有关。感谢@Kevin Ballard提醒。


4
"typedef重新定义"?你确定没有漏掉头文件保护而重复引入同一个头文件吗? - Lily Ballard
1
这段代码编译没有问题。你能复制粘贴你的实际代码吗? - Timothy Jones
2个回答

7

这是一个很好的例子,解释了为什么需要头文件保护:

#ifndef MY_HEADER_FILE
#define MY_HEADER_FILE

typedef struct a A;
typedef struct b B;
/* ... */

#endif

1

现在你已经添加了分号,我看不出你的代码中有任何错误。你也可以像这样前向声明类型:

struct b;
struct c;

typedef struct a {
    struct b* list;
    struct a* parent;
} A;

typedef struct b {
    A* current;
    struct b* next;
} B;

typedef struct c {
    A* current;
    A* root;
} C;

你的方法也可以,避免了多次输入 struct


我能看到它们吗?也许他编辑了它...但我看到了分号。 - DanRedux
@Bort:对我来说它可以编译。 - Ed S.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接