版权声明:本文为博主原创文章,遵循 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
总结:工程结构尽量按照层次分,不要相互依赖,应该一级一级地提供接口。