簡體   English   中英

C 未知類型名稱“my_structure”

[英]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 ,我們得到以下事件序列:

  1. UTILSH已定義
  2. MAINH已定義
  3. 因為UTILSH已經定義了,我們不再處理my_struct.h ,所以 typedef 沒有被處理
  4. void some_func(my_structure *x); 被處理。
  5. 現在處理typedef

因此,在預處理之后,您的編譯器會看到以下聲明序列:

...
void some_func(my_structure *x);
...
typedef struct abcd {...} my_structure;

壞棗。 您要么需要在main.hmy_structure進行前向聲明,要么需要打破這種循環依賴(這是更受歡迎的選項)。 main.h中是否有my_structure.h實際使用的內容? 如果是這樣,您需要將其分解為main.hmy_structure.h包含的單獨文件。

您創建了一個圓形標題包含。 循環包容永遠不會取得任何成就。 它是無限的。 #ifndef包含守衛將在某個不可預測的點打破無限包含圈(取決於哪個頭文件首先包含在.c文件中)。 這就是你的情況。 基本上,您的循環包含被“解析”為首先包含main.h然后包含my_struct.h 這就是main.hmy_struct類型一無所知的原因。

同樣,循環包含永遠不會實現任何目標。 擺脫循環包含。 分層設計您的標題結構:將較低級別的標題包含在更高級別的標題中,但絕不會反過來。 在您的情況下my_struct.h可能是一個較低級別的標頭,這意味着您必須停止將main.h包含到my_struct.h 重新設計您的標題,以便my_struct.h不再需要main.h

該錯誤消息是來自main.h而它包含在my_struct.h ,前my_structure定義。 您應該重新考慮包含路徑,因為main.hmy_struct.h相互包含。

您可能希望main.h文件只包含my_struct.h ,而不要讓my_struct.h包含任何內容。 您實際上是在指示您的 C 編譯器具有無限的 co-include 循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM