头文件相互包含的错误(转载)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/Ronnie_Hu/article/details/78694246
考虑以下情况:

1)secret.h

#ifndef _SECRET_H_
#define _SECRET_H_
 
#include "pub_header.h" 
 
typedef struct _SECRET_Obj_t_
{
    unsigned int counter; // counter
    bool flag;            // flag
} SECRET_Obj_t;
 
#endif

2)interface_secret.h
#ifndef _INTERFACE_SECRET_H_
#define _INTERFACE_SECRET_H_
 
#include "pub_header.h"
 
bool SECRET_fun(SECRET_Obj_t *sp);
 
#endif

3)pub_header.h
#ifndef _PUB_HEADER_H_
#define _PUB_HEADER_H_
 
#include "secret.h"
#include "interface_secret.h"
 
#endif
4)secret.c

#include "secret.h"
 
bool SECRET_fun(SECRET_Obj_t *sp)
{
    return (sp->flag);
} // end of SECRET_fun()

编译结果:
interface_secret.h(6) : error C2065: 'SECRET_Obj_t' : undeclared identifier


在pub_header.h中互换#include "secret.h"和#include "interface_secret.h"的先后顺序不能解决问题。
--------------------------------------------------------------------------------------------------------------------

问题分析:

头文件并不直接参加编译和链接,但是编译器在编译源文件时,需要将其中包含的头文件展开。这样一来,编译器在编译secret.c时,需先展开secret.h,进而转去先展开pub_header.h,再进而转去先展开interface_secret.h,也就是说interface_secret.h最先被展开,因而SECRET_Obj_t未被定义。

---------------------------------------------------------------------------------------------------------------------

解决办法一:将#include "pub_header.h"从secret.h移到secret.c

分析:编译器在编译secret.c时,需先展开secret.h和pub_header.h,而secret.h未包含其他文件,因而SECRET_Obj_t被定义。

解决方法二:将secret.c文件中的#include "secret.h"改为#include "interface_secret.h"

分析:编译器在编译secret.c时,需先展开interface_secret.h,进而转去先展开pub_header.h,再进而转去先展开secret.h,也就是说secret.h会最先被展开,因而SECRET_Obj_t被定义。


————————————————
版权声明:本文为CSDN博主「Ronnie_Hu」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Ronnie_Hu/article/details/78694246

 

 

 

总结:工程结构尽量按照层次分,不要相互依赖,应该一级一级地提供接口。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值