考虑以下情况:
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
--------------------------------------------------------------------------------------------------------------------
问题分析:
头文件并不直接参加编译和链接,但是编译器在编译源文件时,需要将其中包含的头文件展开。这样一来,编译器在编译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被定义。