简体   繁体   English

定义结构时避免“ typedef的重新定义”警告

[英]Avoiding “redefinition of typedef” warnings when defining structs

I'm defining some structs which reference eachother, and typedef'ing the structs before using them, so each struct is 'aware' of the others (was getting compilation errors without this). 我定义了一些互相引用的结构,并在使用它们之前对这些结构进行了类型定义,因此每个结构都“意识到”其他结构(如果没有此结构,则会出现编译错误)。 Not sure if this is necessary, or correct. 不知道这是否必要或正确。

Now when compiling with gcc, I'm getting "redefinition of typedef" warnings. 现在,使用gcc进行编译时,我收到“ typedef的重新定义”警告。 What's the correct way to go about this? 解决这个问题的正确方法是什么?

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

UPDATE: Dumb, bad copy-pasting resulted in this header being included twice in another file. 更新:愚蠢的,错误的粘贴粘贴导致此标头两次包含在另一个文件中。 I'm new to C and thought it must have something to do with having the structs in the file twice. 我是C语言的新手,并认为它与文件中的结构两次有关。 Thanks @Kevin Ballard for the heads up. 感谢@Kevin Ballard的注意。

This is a good example of why header/include guards are needed: 这是为什么需要标头/包含防护的一个很好的例子:

#ifndef MY_HEADER_FILE
#define MY_HEADER_FILE

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

#endif

There is no error in your code that I can see now that you have added the semi-colons. 现在,您已经添加了分号,我可以看到您的代码中没有错误。 You can also just forward declare the types like so: 您也可以像这样向前声明类型:

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;

Your way is fine though, avoids typing struct a few times. 但是,您的方法很好,避免多次键入struct

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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