0

在: http: //www.learncpp.com/cpp-tutorial/110-a-first-look-at-the-preprocessor/

在 Header guards 下,有这些代码片段:

添加.h:

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

减去.h:

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

主.cpp:

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

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

谢谢。

4

4 回答 4

5

该示例正下方的行解释了它。您的mymath.h文件应如下所示:

#ifndef MYMATH_H
#define MYMATH_H

// your declarations here

#endif

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

于 2011-01-22T17:26:32.657 回答
4

如果您使用 MS VC++ 或标准方式,请使用 #pragma 一次

在 mymath.h 里面

#ifndef MYMATH_H
#define MYMATH_H

[code here]

#endif // MYMATH_H
于 2011-01-22T17:25:33.127 回答
2

如果所有头文件都有header guards,如果它们包含两次就可以了。第二个和所有后续包含只会添加空行,不会有任何代码重复。只要确保它mymath.h也有头后卫。

于 2011-01-22T17:26:34.833 回答
1

你应该把你的标题保护放在任何标题中,也在 mymath.h 中。

于 2011-01-22T17:23:27.363 回答