为什么在C ++头文件中使用#ifndef和#define? [英] Why are #ifndef and #define used in C++ header files?

查看:217
本文介绍了为什么在C ++头文件中使用#ifndef和#define?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常在头文件的开头看到这样的代码:

I have been seeing code like this usually in the start of header files:

#ifndef HEADERFILE_H
#define HEADERFILE_H

在文件末尾是

#endif

这是什么目的?

推荐答案

这些被称为#include警卫

一旦包含标头,它就会检查唯一值(在这种情况下为 HEADERFILE_H )。然后,如果未定义,它将定义它并继续到页面的其余部分。

Once the header is included, it checks if a unique value (in this case HEADERFILE_H) is defined. Then if it's not defined, it defines it and continues to the rest of the page.

再次包含代码时,第一个 ifndef 失败,导致文件为空。

When the code is included again, the first ifndef fails, resulting in a blank file.

这样可以防止对任何标识符(例如类型,枚举和静态变量)进行双重声明。

That prevents double declaration of any identifiers such as types, enums and static variables.

这篇关于为什么在C ++头文件中使用#ifndef和#define?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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