有两个头文件a.h和b.h
a.h中
#pragma once
#ifndef _A_H_
#define _A_H_
#include "b.h"
struct AInfo
{
int a;
int b;
};
#endif
b.h中
#pragma once
#ifndef _B_H_
#define _B_H_
#include "a.h"
class B
{
public:
void fun1(AInfo aInfo, int n );
};
#endif
然后有两个源文件a.cpp和b.cpp
a.cpp中
#include "a.h"
......
b.cpp中
#include "b.h"
......
编译项目时会报错,AInfo没有定义。
a.cpp中包含头文件a.h,在编译之前,会在a.cpp中展开a.h而a.h又包含了b.h,所以也展开b.h,这时a.cpp就变成了类似下面的样子:
class B
{
public:
void fun1(AInfo aInfo, int n );
};
struct AInfo
{
int a;
int b;
};
......
此时,在结构体AInfo声明之前,fun1中就用到了它,所以会产生AInfo没有定义的错误信息。所以应该将结构体的定义放在引用头文件#include "b.h"之前就可以了。即将a.h改成如下:
#pragma once
#ifndef _A_H_
#define _A_H_
struct AInfo
{
int a;
int b;
};
#include "b.h"
#endif
同样,展开b.cpp如下:
struct AInfo
{
int a;
int b;
};
class B
{
public:
void fun1(AInfo aInfo, int n );
};
......
C/C++ 中头文件习惯使用 #ifndef ... #define ... #endif
这样的一组预处理标识符来防止重复包含,如果不使用的话,两个头文件相互包含,就出现递归包含。
参考:https://blog.csdn.net/hazir/article/details/38600419 C/C++ 中头文件相互包含引发的问题