前言
- 本博文基於MDK5.26的C環境編寫,不過跟芯片沒關係,是軟件調試出現的問題;
- 本博文並一定適合其他原因引起的未定義錯誤,僅適合“已經定義了xxx,但卻報沒定義的錯”這種情況;
- 如有不足之處,還請多多指教;
迷之錯誤:error: #20: identifier “xxx” is undefined
實際上我是定義了xxx的;但是編譯器卻一直報錯;
故事是這樣的:
我定義了a.h,b.h,c.h。其中a.h和b.h都是子功能頭文件,而c.h是包含所有項目頭文件的集合體,比如數據類型,當然也包含a.h和b.h;關係看下面代碼;
/* c.h */
#ifndef C_H
#define C_H
#include "Type.h"
#include "a.h"
#include "b.h"
#include "x.h"
#include "xx.h"
#include "xxx.h"
#endif /* C_H */
/* a.h */
#include "c.h" //爲了讓頭文件看起來更簡單,我爲每一個子功能頭文件都包含了c.h,這將是後來引起錯誤的地方;
typedef struct ITEM
{
//各成員
}Item_t;
/* b.h */
#include "c.h"
struct BLOCK
{
Item_t Item1; // 這裏我引用了a.h中的Item_t類型,並定義了變量;這裏就是報錯的地方;
//其他成員;
}Block;
這種情況下就出了問題,那麼問題在哪兒哪?
在b.h中的Item_t Item1; ** ,這個地方就是報錯的地方;顯示error: #20: identifier “Item_t” is undefined,順着這兒往上看的,這個問題就出在了a.h裏的這個#include “c.h” **;對於a.h來說,調用的 **#include “c.h”**可以展開爲:
/* a.h */
#include "Type.h"
#include "a.h"
#include "b.h"
#include "x.h"
#include "xx.h"
#include "xxx.h"
typedef struct ITEM
{
//各成員
}Item_t;
所以錯誤的地方是:相對於a.h文件來說,在定義ITEM結構體之前就已經調用了b.h,而b.h裏又有對Item_t類型變量的定義,所以就出順序邏輯錯誤;
解決辦法
在大工程中儘量避免在頭文件中使用總頭文件;所以這裏就在a.h和b.h中去掉包含的c.h文件,需要什麼頭文件就用什麼頭文件;所以修改完之後是:
/* a.h */
#include "Type.h"
#include "x.h"
#include "xx.h"
#include "xxx.h"
typedef struct ITEM
{
//各成員
}Item_t;
/* b.h */
#include "a.h"
#include "x.h"
#include "xx.h"
#include "xxx.h"
struct BLOCK
{
Item_t Item1;
//其他成員;
}Block;