C ++和C中的标题保护 [英] Header guards in C++ and C
问题描述
在 LearnCpp.com | 1.10 —首先看一下预处理器.在标题卫士下,有以下代码段:
At LearnCpp.com | 1.10 — A first look at the preprocessor. Under Header guards, there are those code snippets:
add.h:
#include "mymath.h"
int add(int x, int y);
subtract.h:
subtract.h:
#include "mymath.h"
int subtract(int x, int y);
main.cpp:
#include "add.h"
#include "subtract.h"
在实施标头防护时,其说明如下:
In implementing the header guard, it is mentioned as follows:
#ifndef ADD_H
#define ADD_H
// your declarations here
#endif
- 这里的声明会是什么?而且,
int main()
应该在#endif
之后吗? - 要添加
_H
约定还是必须做的事? - What could the declaration be here? And, should
int main()
come after#endif
? - Is adding
_H
a convention or a must do thing?
谢谢.
推荐答案
FILENAME_H
是一个约定.如果确实需要,可以将#ifndef FLUFFY_KITTENS
用作标题保护(假设未在其他任何地方定义),但是如果在其他地方定义它(例如,某物或其他东西的小猫数量),那将是一个棘手的错误.
The FILENAME_H
is a convention. If you really wanted, you could use #ifndef FLUFFY_KITTENS
as a header guard (provided it was not defined anywhere else), but that would be a tricky bug if you defined it somewhere else, say as the number of kittens for something or other.
在头文件add.h中,声明实际上位于#ifndef
和#endif
之间.
In the header file add.h the declarations are literally between #ifndef
and #endif
.
#ifndef ADD_H
#define ADD_H
#include "mymath.h"
int add(int x, int y);
#endif
最后,int main()
不应放在头文件中.它应该始终在.cpp
文件中.
Finally, int main()
shouldn't be in a header file. It should always be in a .cpp
file.
要清除它:
#ifndef ADD_H
的基本含义是如果文件或包含的文件中未包含#defined
ADD_H,则在#ifndef
和#endif
伪指令之间编译代码".因此,如果您尝试在.cpp
文件中多次#include "add.h"
,则编译器将看到ADD_H已经是#defined
的内容,并且将忽略#ifndef
和#endif
之间的代码.标头防护仅防止标头文件多次包含在同一.cpp
文件中.标头防护不会阻止其他.cpp
文件包含标头文件.但是所有.cpp
文件只能包含受保护的头文件一次.
#ifndef ADD_H
basically means "if ADD_H has not been #defined
in the file or in an included file, then compile the code between #ifndef
and #endif
directives". So if you try to #include "add.h"
more than once in a .cpp
file, the compiler will see what the ADD_H was already #defined
and will ignore the code between #ifndef
and #endif
. Header guards only prevent a header file from being included multiple times in the same .cpp
file. Header guards don't prevent other .cpp
files from including the header file. But all .cpp
files can include the guarded header file only once.
这篇关于C ++和C中的标题保护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!