2012-03-13 142 views
1

我定义了一些引用彼此的结构,并在使用它们之前对结构进行typedef'ing,因此每个结构都“知道”其他结构(没有这样的编译错误)。不知道这是必要的还是正确的。在定义结构时避免“重定义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; 
}; 

UPDATE: 哑,坏的复制粘贴导致这个头在另一个文件中被包含两次。我是C新手,并且认为它必须与文件中的结构两次有关。感谢@Kevin Ballard的领袖。

+4

“的typedef重新定义”?你确定你没有标头守卫两次导入相同的头文件吗? – 2012-03-13 00:09:05

+1

这段代码编译得很好。你能复制并粘贴你的实际代码吗? – 2012-03-13 00:09:08

回答

5

这也是为什么头/包括需要守卫一个很好的例子:

#ifndef MY_HEADER_FILE 
#define MY_HEADER_FILE 

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

#endif 
0

您的代码中没有错误,我现在可以看到您添加了分号。几次

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:您也可以只向前声明的类型,像这样。

+0

修正了,手工复制代码时忘记包含它们。 – Bort 2012-03-13 00:08:42

+0

我能看到他们吗?也许他编辑过它..但我看到了分号。 – DanRedux 2012-03-13 00:09:32

+0

@Bort:它为我编译。 – 2012-03-13 00:09:42