C++头文件保护

问题????

add.h

#include "mymath.h"
int add(int x,int y);

subtract.h

   
#include "mymath.h"
int subtract(int x,int y);

main.cpp

#include "add.h"
#include "subtract.h"

当我们有add.h,它带来了两个mymath.h和原型的add()。

当我们有subtract.h,它带来两个mymath.h(再次)和原型减去()。

因此,mymath.h的所有内容将被包含了两次,这将导致编译器报错。

解决方法:

Header guard 直译是头文件保护

在定义头文件是使用 头文件保护 例:
#ifndef SOME_UNIQUE_NAME_HERE
#define SOME_UNIQUE_NAME_HERE
// your declarations here
#endif