预处理器指令#ifndef for C / C ++代码 [英] Preprocessor directive #ifndef for C/C++ code

查看:306
本文介绍了预处理器指令#ifndef for C / C ++代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在eclipse中,每当我创建一个新的C ++类,或者 C 头文件时,我得到以下类型的结构。说我创建头文件example.h,我得到这个:

In eclipse, whenever I create a new C++ class, or C header file, I get the following type of structure. Say I create header file example.h, I get this:

/*Comments*/
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
/* Place to put all of my definitions etc. */
#endif

我认为ifndef说如果没有定义EXAMPLE_H_,定义它,根据你用来编译和链接你的项目的工具,这可能是有用的。但是,我有两个问题:

I think ifndef is saying that if EXAMPLE_H_ isn't defined, define it, which may be useful depending on what tool you are using to compile and link your project. However, I have two questions:


  1. 这是否相当普遍?我经常看不到。使用该标题是一个好主意,或者您应该直接跳转到定义代码。

  1. Is this fairly common? I don't see it too often. And is it a good idea to use that rubric, or should you just jump right into defining your code.

什么是EXAMPLE_H_?为什么不是example.h,或者只是例子?有没有什么特别之处,还是可能只是eclipse喜欢自动构建项目的工具?

What is EXAMPLE_H_ exactly? Why not example.h, or just example? Is there anything special about that, or could is just be an artifact of how eclipse prefers to auto-build projects?


推荐答案

这是一个常见的结构。目的是将头文件的内容仅包含在翻译单元中一次,即使物理头文件被包含多于一次。这可能会发生,例如,如果您将头文件直接包含在源文件中,并且还通过另一个标头间接包含。

This is a common construct. The intent is to include the contents of the header file in the translation unit only once, even if the physical header file is included more than once. This can happen, for example, if you include the header directly in your source file, and it's also indirectly included via another header.

将#ifndef包装器放在内容上这意味着编译器只能解析标头的内容一次,并避免重新定义错误。

Putting the #ifndef wrapper around the contents means the compiler only parses the header's contents once, and avoids redefinition errors.

有些编译器允许#pragma once做同样的事情,但是#ifndef构造工作无处不在。

Some compilers allow "#pragma once" to do the same thing, but the #ifndef construct works everywhere.

这篇关于预处理器指令#ifndef for C / C ++代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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