2012-03-13 149 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