C++ - 如何避免此标题出现两次?

Sim*_*ity 0 c++ header include-guards

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

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

add.h:

#include "mymath.h"
int add(int x, int y);
Run Code Online (Sandbox Code Playgroud)

subtract.h:

#include "mymath.h"
int subtract(int x, int y);
Run Code Online (Sandbox Code Playgroud)

main.cpp中:

#include "add.h"
#include "subtract.h"
Run Code Online (Sandbox Code Playgroud)

我怎样才能避免#include "mymath.h"出现两次main.cpp

谢谢.

Jar*_*edC 5

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

#ifndef MYMATH_H
#define MYMATH_H

// your declarations here

#endif
Run Code Online (Sandbox Code Playgroud)

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