File1.h,file2.h,file3.h,file4.h,file5.h,main.cpp
那么:file3.h包含file1.h,file2.h,file4.h包含file1.h,file2.h,file5.h包含file3.h,file4.h。如许就会导致在file5中对file1和file2的反复包含,编译时就会报错。
解决方法:
1:应用#ifndef
#define
#endif
即每个文件在定义时都写成以下情势(以file1.h为例):
#ifndefH_FILE1
#defineH_FILE1
#include
#include
…..
#endif
File3.h:#ifndefH_FILE3
#defineH_FILE3
#include
#include
#inlcude”file1.h”
#include”file2.h”
…..
#endif
方法二:在每个文件的头部定义:#pragmaonce(用于解释本文件中的内容只应用一次)
例:fiel1.h:
#pragmaonce
#include
#include
…..
File3.h:
#pragmaonce
#include
#include
#include”file1.h”
…..
#ifndef BASE_H//如果没有定义过 BASE_H ,就编译下面的代码#define BASE_H//定义这个宏
#endif
在每一个.h文件,都使用这个编译指令。即使多次 #include,也不会重复包含。
#ifndef BASE_H
如果首次 #include 这个.h文件,BASE_H 没有被定义,所以这个.h文件就包含进来参与编译,同时定义了BASE_H
后续再次 #include 这个 .h 文件,由于 BASE_H已经定义过,所以在对应的 #endif 前的代码不参与编译,就不会出现两个基本信息结构体
----------------------
除了头文件的包含,ifdef 也会用在其他地方,比如判断编译环境,
#ifndef _WIN64
#define NULL 0
#else
#define NULL 0LL
#endif
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)