头文件为什么要加#ifndef #define #endif

当你用VC的菜单新增一个类,你会发现自动生成的代码总是类似下面的样子:

#if !defined(AFX_XXXX__INCLUDED_)

#define  AFX_XXXX__INCLUDED_

具体代码

#endif

       这是为了防止头文件被重复包含。重复包含可以用下面的例子来说明:比如有个头文件a.h,里面有个函数Fa;另一个头文件b.h,里面有函数Fb, Fb的实现需要用到Fa,则b.h中需要包含a.h;有个cpp文件中的函数需要用到FaFb,则需要包含a.hb.h,此时a.h就发生了重复包含。编译程序,出现如下错误:

error C2084: function 'bool __cdecl Fa()' already has a body

解决办法是在a.h的中加入:

#ifndef A

#define A

原来的代码

#endif

 

示例源代码清单如下:

// a.h

#ifndef A

#define A

 

bool AorB(bool a)

{

       return a;

}

 

#endif

 

// b.h

#include "a.h"

 

bool CorD(bool a)

{

       return AorB(a);

}

 

// a.cpp

#include "a.h"

#include "b.h"

 

int main()

{

       bool a = 0;

       bool b = AorB(a);

       bool c = CorD(b);

 

       getchar();

       return 0;

}

你可能感兴趣的:(头文件为什么要加#ifndef #define #endif)