C ++ - 标题保护 [英] C++ - header guards
问题描述
在: http://www.learncpp.com/ cpp-tutorial / 110-a-first-look-at-the-preprocessor /
在标题警告那些代码片段:
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"
$ b b
在实施标头警告时,提到如下:
#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?
p>
推荐答案
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.
#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
基本上意味着如果此文件尚未查看,请查看。如果已经查看,那么它将跳过文件中的所有内容。所以如果你包括它两次,那么当它第一次包括时,编译器将看到添加函数是什么。它还将尝试包括 mymath.h
文件IF,如果还没有被查看。
The #ifndef
basically means 'if this file has not already been looked at, look at it'. If it has been looked at, then it will skip everything in the file. So if you include it twice, then when it is first included the compiler will see what the add function is. It will also try to include the mymath.h
file IF that hasn't been looked at already.
这篇关于C ++ - 标题保护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!