实际已经定义却出现 error: #20: identifier “xxx“ is undefined 的错误

原文:https://blog.csdn.net/wuyuzun/article/details/97803640

前言

  1. 本博文基于MDK5.26的C环境编写,不过跟芯片没关系,是软件调试出现的问题;
  2. 本博文并一定适合其他原因引起的未定义错误,仅适合“已经定义了xxx,但却报没定义的错”这种情况;
  3. 如有不足之处,还请多多指教;

迷之错误: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;
  • 26
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值