eclipse自动生成的.h文件守卫
在 Eclipse 中,当创建 C++ 类时,会自动生成带有保护 XXXX_H_
的 .h 文件。根据我有限的经验,守卫始终采用 XXXX_H
的形式,而没有尾随 _
。
所以,我只是好奇为什么 _
在那里。
提前致谢。
In eclipse, when a c++ class is created, .h file's auto-generated with guard XXXX_H_
. In my limited, little experience, the guard is always be in the form of XXXX_H
without the trailing _
.
So, I'm just curious and wondering why the _
is over there.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用相当现代的编译器,则可以用更优雅的指令
#pragma Once
替换这些保护。要修改 Eclipse CDT 中的标头模板,请转到“Window/Preferences/C++/Code Templates/Files/ C++ 头文件/默认 C++ 头模板”并放在那里
之后,您的新 h 文件将从如下所示开始:
If you use a reasonably modern compiler, you can replace these guards with more elegant directive
#pragma once
To modify the header's template in Eclipse CDT, go to "Window/Preferences/C++/Code Templates/Files/C++ Header File/Default C++ header template" and put there
After that your new h files will start from something like this:
可能会添加尾随
_
以避免与用户定义的标识符发生冲突。例如,您可能有一个名为get.h
的头文件,同时您也可以拥有自己的名为GET_H
的宏(或变量或函数)。因此,在get.h
中使用GET_H
进行包含保护很容易导致问题。标准库头文件可能会使用前导
_
来命名其内部宏,以达到相同的目的 - 避免与用户定义的标识符发生名称冲突。因此,语言规范明确禁止以_
和大写字母开头的用户定义标识符。出于同样的原因,前导_
不能在包含防护的名称中使用。因此,Eclipse 决定使用 尾随
_
来达到同样的目的。它提供了合理级别的名称冲突保护,并且不违反语言规范的要求。The trailing
_
might be added to avoid collision with user-defined identifiers. For example, you might have a header file namedget.h
and at the same time you can conceivably have your own macro (or variable, or function) namedGET_H
. So, usingGET_H
for include guard inget.h
would easily lead to problems.The standard library header files might use a leading
_
to name its internal macros for the very same purpose - to avoid name collision with user-defined identifiers. For that reason, the language specification explicitly prohibits user-defined identifiers that begin with_
and a capital letter. And for the very same reason, the leading_
cannot be used in the names of include guards.So, Eclipse decided to use a trailing
_
for the very same purpose. It provides a reasonable level of protection from name collisions and does not violate the requirements of language specification.包含防护的名称是什么并不重要,只要它在所有头文件中是唯一的即可。
XXXX_H_
很常见,XXXX_H
也是如此。有时会使用 GUID。It doesn't matter what the name of the inclusion guard is, so long as it is unique across all header files.
XXXX_H_
is common, as isXXXX_H
. GUIDs are occasionally used.名称无关紧要,只需唯一即可。我的猜测是,添加它是为了减少与用户创建的定义发生冲突的可能性。
The name is irrelevant, it just needs to be unique. My guess is that it was added to make it less likely to have a collision with user-created defines.