1

There has been a few cases where I've seen preprocessor code like the following:

#ifndef TOKEN
#define TOKEN
#endif

To me, it seems that in this situation (I'm aware of it's use when wrapped around items other than it's self (including include guards for those who are still answering)), it is redundant to check if TOKEN is already defined before defining it. If I were to just #define it, without the checks, the result is the same.

Is there a common reason for this? Compilation times? Reserving the block for future additions?

Thanks.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
Razioark
  • 23
  • 4

4 Answers4

4

Because you may get macro redefinition warnings otherwise. For example, we have some third party dll's who have headers with things like the following.

#define PI 3.14

As these are defined in third party headers, we have no control over them and cannot remove or rename them. If we also try to define Pi ourselves, we would get a macro redefinition warning. So you have two options,

1) Use their macro, and guard against redefinition

#ifndef PI
#define PI 3.14
#endif

2) Remove their definition, then define your own

#ifdef PI
#undef PI
#endif
#define PI 3.14
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • That makes sense, thanks. I didn't get any errors as I hadn't thought to add a value to either #define. My mind is eased. :) – Razioark Oct 13 '14 at 14:01
3

One cool thing you can do with macros is define them on the command line, for gcc I often use

gcc source.c -DMY_PI=6.5

and then in my code

#ifndef MY_PI
#define MY_PI 3.1415
#endif

This allows me to compile the same code with many different definitions of MY_PI but also allows for a default value.

ilent2
  • 5,171
  • 3
  • 21
  • 30
  • 2
    And of course, I really like setting PI to 6.5, ...? – ilent2 Oct 13 '14 at 13:55
  • I've never been sure what GCC really was, but that's good to know, I'll keep that in mind. That is the kind of thing, say UE4 Editor, would do when building the engine/game for certain targets/settings, right? – Razioark Oct 13 '14 at 14:03
1

Your exact example is often used for multiple inclusion protection (include guard) . In large code bases, you may have an h file that's included in multiple spots, and this construct is used to avoid the redefinition error. In modern compilers, it can be replaced with

#pragma once

at the top of the file.

svvitale
  • 111
  • 1
  • 8
0

This is include guard.

In the C and C++ programming languages, an #include guard, sometimes called a macro guard, is a particular construct used to avoid the problem of double inclusion when dealing with the include directive. The addition of #include guards to a header file is one way to make that file idempotent.

Kindly check below for details:

http://en.wikipedia.org/wiki/Include_guard

C++ - header guards

Community
  • 1
  • 1
iampranabroy
  • 1,716
  • 1
  • 15
  • 11