开发者

eclipse's auto-generated .h file guards

In ecl开发者_StackOverflowipse, when a c++ class is created, .h file's auto-generated with guard XXXX_H_. In my limited, little experience, the guard is always be in the form of XXXX_H without the trailing _.

So, I'm just curious and wondering why the _ is over there.

Thanks in advance.


If you use a reasonably modern compiler, you can replace these guards with more elegant directive #pragma once

To modify the header's template in Eclipse CDT, go to "Window/Preferences/C++/Code Templates/Files/C++ Header File/Default C++ header template" and put there

${filecomment}

#pragma once

${typecomment}
${declarations}

After that your new h files will start from something like this:

/*
 * FileServer.h
 *
 *  Created on: Feb 26, 2011
 *      Author: krit
 */

#pragma once


The trailing _ might be added to avoid collision with user-defined identifiers. For example, you might have a header file named get.h and at the same time you can conceivably have your own macro (or variable, or function) named GET_H. So, using GET_H for include guard in get.h would easily lead to problems.

The standard library header files might use a leading _ to name its internal macros for the very same purpose - to avoid name collision with user-defined identifiers. For that reason, the language specification explicitly prohibits user-defined identifiers that begin with _ and a capital letter. And for the very same reason, the leading _ cannot be used in the names of include guards.

So, Eclipse decided to use a trailing _ for the very same purpose. It provides a reasonable level of protection from name collisions and does not violate the requirements of language specification.


It doesn't matter what the name of the inclusion guard is, so long as it is unique across all header files.

XXXX_H_ is common, as is XXXX_H. GUIDs are occasionally used.


The name is irrelevant, it just needs to be unique. My guess is that it was added to make it less likely to have a collision with user-created defines.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜