2011-01-22 55 views
0

在:http://www.learncpp.com/cpp-tutorial/110-a-first-look-at-the-preprocessor/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" 

如何避免#include "mymath.h"main.cpp中出现两次?

感谢。

+0

为什么你想避免它包括两次? – sth 2011-01-22 17:24:54

回答

4

右低于实施例中的行解释。你mymath.h文件应该是这样的:

#ifndef MYMATH_H 
#define MYMATH_H 

// your declarations here 

#endif 

每头文件应该遵循这个基本格式。这允许任何需要它的文件(头文件和源文件)都包含头文件,但实际的声明在每个源文件中最多只能包含一次

1

你应该把你的头文件放在任何头文件中,也可以放在mymath.h文件中。

4

使用#pragma一旦如果使用MS VC++或标准方式

内部mymath.h

#ifndef MYMATH_H 
#define MYMATH_H 

[code here] 

#endif // MYMATH_H 
2

这没关系,如果他们包括两次,如果全部头文件有标头警卫。第二个和所有后续的包含只会添加空行,并且不会有任何代码重复。只要确保mymath.h也有标头警卫。