Purpose of Header guards

一笑奈何 提交于 2019-11-26 06:47:39

问题


In C++ what is the purpose of header guard in C++ program.

From net i found that is for preventing including files again and again but how do header guard guarantee this.


回答1:


The guard header (or more conventionally "include guard") is to prevent problems if header file is included more than once; e.g.

#ifndef MARKER
#define MARKER
// declarations 
#endif

The first time this file is #include-ed, the MARKER preprocessor symbol will be undefined, so the preprocessor will define the symbol, and the following declarations will included in the source code seen by the compiler. On subsequent #include's, the MARKER symbol will be defined, and hence everything within the #ifnde / #endif will be removed by the preprocessor.

For this to work properly, the MARKER symbol needs to be different for each header file that might possibly be #include-ed.

The reason this kind of thing is necessary is that it is illegal in C / C++ to define a type or function with the same name more than once in a compilation unit. The guard allows a header file to #include other header files without worrying that this might cause some declarations to be included multiple times.


In short, it doesn't prevent you from #include-ing a file again and again. Rather, it allows you to do this without causing compilation errors.




回答2:


The purpose of header guards is to prevent issues where some code may appear only once per translation unit.

One example is a struct. You cannot redefine a struct even if the second definition is identical. So, if you try to compile the following:

struct foo { int x; };
struct foo { int x; };

The compiler will fail because of the redefinition.

It can be hard to guarantee you only include a header one time (this happens when headers include other headers). If your header has struct definition, this will cause the compile to fail. Header guards are the easy trick so that even if a header is included multiple times, it's contents only appear a single time.



来源:https://stackoverflow.com/questions/2979384/purpose-of-header-guards

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