原文:https://blog.csdn.net/wuyuzun/article/details/97803640
前言
- 本博文基于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 */
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
/* a.h */
#include "c.h" //为了让头文件看起来更简单,我为每一个子功能头文件都包含了c.h,这将是后来引起错误的地方;
typedef struct ITEM
{
//各成员
}Item_t;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
/* b.h */
#include "c.h"
struct BLOCK
{
Item_t Item1; // 这里我引用了a.h中的Item_t类型,并定义了变量;这里就是报错的地方;
//其他成员;
}Block;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
这种情况下就出了问题,那么问题在哪儿哪?
在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;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
所以错误的地方是:相对于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;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
/* b.h */
#include "a.h"
#include "x.h"
#include "xx.h"
#include "xxx.h"
struct BLOCK
{
Item_t Item1;
//其他成员;
}Block;