2013-07-28 76 views
3

我想通過函數中的struct指針。我在file1.h中有一個typedef,並且只想將這個頭文件包含到file2.c中,因爲file2.h只需要指針。在C++中,我會像我這樣寫,但使用C99它不起作用。如果有人有任何建議如何通過struct沒有完整定義的指針,將不勝感激。編譯器 - gcc。C正向聲明頭結構中的結構

file1.h

typedef struct 
{ 
    ... 
} NEW_STRUCT;

file2.h

struct NEW_STRUCT; 

void foo(NEW_STRUCT *new_struct); //error: unknown type name 'NEW_STRUCT'

file2.c中

#include "file2.h" 

#include "file1.h" 

void foo(NEW_STRUCT *new_struct) 
{ 
    ... 
}
+4

* 「這是行不通的。」 *解釋說。你有沒有編譯錯誤?一個鏈接器錯誤?運行時崩潰?發生了什麼? – abelenky

+0

對不起,忘了。它既不像這樣編譯,也不是如果我將'struct'添加到函數參數中,那麼錯誤將更改爲「函數foo'參數類型不匹配」。 – PovilasG

回答

9

我認爲你必須要命名您的結構,並做的向前聲明它和後重新typedef它。

第一個文件:

typedef struct structName {} t_structName; 

第二個文件:

struct stuctName; 
    typedef struct structName t_structName 
+0

希望得到一個不涉及re typedef'ing的解決方案,但我必須接受這一點。 – PovilasG

0

你可以試試這個:

file1.h

typedef struct _NEW_STRUCT // changed! 
{ 
    ... 
} NEW_STRUCT; 

file2.h

struct _NEW_STRUCT; // changed! 

void foo(struct _NEW_STRUCT *new_struct); // changed! 

file2.c中

#include "file2.h" 
#include "file1.h" 

void foo(NEW_STRUCT *new_struct) 
{ 
    ... 
}