[英]C Unknown type name 'my_structure'
我有這個代碼:
main.h
#ifndef MAINH
#define MAINH
...
#include "my_struct.h"
void some_func(my_structure *x);
...
#endif
和
my_struct.h
#ifndef UTILSH
#define UTILSH
...
#include "main.h"
...
typedef struct abcd {
int a;
} my_structure;
...
#endif
但是當我嘗試編譯時得到這個: error: unknown type name 'my_structure'
知道為什么嗎?
由於您訂購包含的方式,編譯器會看到void some_func(my_structure *x);
在它看到typedef struct abcd { int a; } my_structure;
typedef struct abcd { int a; } my_structure;
.
讓我們來看看這個。
假設首先處理my_struct.h
,我們得到以下事件序列:
UTILSH
已定義MAINH
已定義UTILSH
已經定義了,我們不再處理my_struct.h
,所以 typedef 沒有被處理void some_func(my_structure *x);
被處理。typedef
。因此,在預處理之后,您的編譯器會看到以下聲明序列:
...
void some_func(my_structure *x);
...
typedef struct abcd {...} my_structure;
壞棗。 您要么需要在main.h
對my_structure
進行前向聲明,要么需要打破這種循環依賴(這是更受歡迎的選項)。 main.h
中是否有my_structure.h
實際使用的內容? 如果是這樣,您需要將其分解為main.h
和my_structure.h
包含的單獨文件。
您創建了一個圓形標題包含。 循環包容永遠不會取得任何成就。 它是無限的。 #ifndef
包含守衛將在某個不可預測的點打破無限包含圈(取決於哪個頭文件首先包含在.c
文件中)。 這就是你的情況。 基本上,您的循環包含被“解析”為首先包含main.h
然后包含my_struct.h
。 這就是main.h
對my_struct
類型一無所知的原因。
同樣,循環包含永遠不會實現任何目標。 擺脫循環包含。 分層設計您的標題結構:將較低級別的標題包含在更高級別的標題中,但絕不會反過來。 在您的情況下my_struct.h
可能是一個較低級別的標頭,這意味着您必須停止將main.h
包含到my_struct.h
。 重新設計您的標題,以便my_struct.h
不再需要main.h
。
該錯誤消息是來自main.h
而它包含在my_struct.h
,前my_structure
定義。 您應該重新考慮包含路徑,因為main.h
和my_struct.h
相互包含。
您可能希望main.h
文件只包含my_struct.h
,而不要讓my_struct.h
包含任何內容。 您實際上是在指示您的 C 編譯器具有無限的 co-include 循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.