What is a guard block for a header file in C++?

∥☆過路亽.° 提交于 2021-02-20 11:32:21

问题


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.


回答1:


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:

// Foo.h
#ifndef INCLUDE_FILE_NAME_HERE_H_
#define INCLUDE_FILE_NAME_HERE_H_

class Foo
{
};


#endif

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.




回答2:


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.

// foo.h
#pragma once

int foo(void);
// etc.


来源:https://stackoverflow.com/questions/7841788/what-is-a-guard-block-for-a-header-file-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!