C++ 中头文件的保护块是什么?
我正在尝试使用 Code::Blocks IDE 创建一个 C++ 类,并且有一个名为“Guard block”的字段。我进行了搜索,但未能找到任何有用的信息。这个字段有什么用?谢谢。
I'm trying to make a C++ class using the Code::Blocks IDE and there is a field called "Guard block." I've done a search and haven't been able to find any useful information. What is this field for? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
保护块用于防止同一编译单元(c++ 文件)多次包含头文件。它们看起来像这样:
如果您在同一个文件中包含多个文件,则最终会出现多个定义错误。在小型项目中没有必要使用包含防护,但在任何中型到大型项目中都变得至关重要。我经常在我编写的任何头文件中使用它。
Guard blocks are used to protect against the inclusion of a header file multiple times by the same compilation unit (c++ file). They look something like this:
If you include the same file multiple files, you will end up with multiple definition error. Using of include guards isn't necessary in small projects but becomes critical in any medium to large sized projects. I use it routinely on any header files I write.
保护块用于防止头文件被多次包含在单个翻译单元中。当您包含许多头文件,而这些头文件又包含通用标准头文件时,这通常是一个问题。
多次包含同一文件的问题在于,它会导致同一符号被定义多次。
保护子句可以使用
#define
和#ifdef
语句来处理,但使用非标准但通用的#pragma Once
则要简单得多。Guard blocks are used to prevent a header file being included multiple times in a single translation unit. This is often a problem when you include a number of header files that in turn include common standard header files.
The problem with multiple inclusions of the same file is that it results in the same symbol being defined multiple times.
Guard clauses can be handled with
#define
and#ifdef
statements but are much simpler with the non-standard, but universal,#pragma once
.