0

So I'm cleaning up some code written by someone else and I've stumbled upon some header related defines that I don't fully understand.

For example in my experience the following has always been the go-to syntax when defining my own header files...

#ifndef SOMEFILE_H
#define SOMEFILE_H

However as I am going over this code I am seeing something slightly similar, but distinctly different...

#ifndef  INCLUDED_SOMEFILE_H
#define  INCLUDED_SOMEFILE_H

What purpose does the INCLUDED portion serve? And under what circumstance would a programmer want to use the later format?

Jeremy S.
  • 1,141
  • 1
  • 7
  • 18

1 Answers1

1

What purpose does the INCLUDED portion serve?

It helps avoid name collisions. There is nothing magical about the identifiers used in these include guards; what you need is consistency. The requirements are basically:

  1. Use the same identifier for both the #ifndef and the #define.
  2. Do not use that identifier anywhere else in your program (outside comments -- there is a reasonable convention to use this identifier in a third place: a comment on the #endif line).

The first requirement is where your confusion (probably) comes from. You probably thought that the identifier had to be the file name in all caps, with the period replaced by an underscore. Not so. Absolutely any identifier could be made to work. You could even use something like

#ifndef I_LIKE_SEE_PLUS
#define I_LIKE_SEE_PLUS

but it's not recommended as it will lead to programmer confusion (emphasis added for those skimming this answer).

The second requirement is presumably the reason someone used "INCLUDED_" in the code you looked at. That coder was probably working under the naming convention in which every include guard identifier starts with "INCLUDED_" and no other identifiers start with that. Under this convention, there is little chance of an include guard identifier accidentally being used elsewhere.

That being said, that convention can be overkill. A simpler, and usually effective, convention is to specify the endings of include guard identifiers: "_H" or "_HPP" or whatever your file naming convention specifies. It's more likely to accidentally violate this convention than the overkill one, but still not all that likely.

And under what circumstance would a programmer want to use the later format?

Pick a convention for your project and stick to it. Use something that works for you (and your team if there is one).

JaMiT
  • 9,693
  • 2
  • 12
  • 26