在C ++中包含头文件两次 [英] including a header file twice in c++

查看:136
本文介绍了在C ++中包含头文件两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在文件中两次包含 iostream 或任何其他头文件会怎样?
我知道编译器不会抛出错误。

What happens if I include iostream or any other header file twice in my file? I know the compiler does not throw error.

代码将被添加两次还是内部会发生什么?

Will the code gets added twice or what happens internally?

当我们包含头文件时实际发生了什么?

What actually happens when we include a header file ?

推荐答案

包含保护可防止编译器实际上两次看到文件的内容。

Include guard prevents the content of the file from being actually seen twice by the compiler.

包含保护基本上是在头文件的开头和结尾处的一组预处理程序的条件指令:

Include guard is basically a set of preprocessor's conditional directives at the beginning and end of a header file:

#ifndef SOME_STRING_H
#define SOME_STRING_H

//...

#endif 

现在,如果您两次包含文件,则第一次循环宏 SOME_STRING_H 未定义,因此文件的内容将由编译器处理并查看。但是,由于 #ifdef 之后的第一件事是 #define ,因此 SOME_STRING_H 已定义,并且下次编译器将看不到头文件的内容。

Now if you include the file twice then first time round macro SOME_STRING_H is not defined and hence the contents of the file is processed and seen by the compiler. However, since the first thing after #ifdef is #define, SOME_STRING_H is defined and the next time round the header file's content is not seen by the compiler.

为避免冲突,在包含保护中使用的宏的名称取决于头文件的名称。

To avoid collisions the name of the macro used in the include guard is made dependent on the name of the header file.

这篇关于在C ++中包含头文件两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆