2

In eclipse, 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.

draw
  • 4,696
  • 6
  • 31
  • 37

4 Answers4

4

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
Krit
  • 548
  • 3
  • 9
  • #pragma once is elegant, except when it doesn't work! – Bo Persson Mar 19 '11 at 06:26
  • Could you please elaborate a bit? – Krit Mar 19 '11 at 09:40
  • Check the answer with the highest score - #pragma once is fine, except when it doesn't work. Sometimes the compiler cannot tell if two files are the same or different. Then what happens? – Bo Persson Mar 19 '11 at 11:19
  • So far I've only found that prior to version 3.4 GCC didn't recognize some specific cases, such as symbolic and hard links. It was fixed long time ago. That's why I was asking if there's anything else that should be considered. – Krit Mar 20 '11 at 17:38
3

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.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
2

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.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
1

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.

EboMike
  • 76,846
  • 14
  • 164
  • 167