2

Being pretty new to C++, I don't quite understand some instructions I encounter such as:

#ifndef BOT_H_
#define BOT_H_

#include "State.h"

/*
    This struct represents your bot in the game of Ants
*/
struct Bot
{
    State state;

    Bot();

    void playGame();    //plays a single game of Ants

    void makeMoves();   //makes moves for a single turn
    void endTurn();     //indicates to the engine that it has made its moves
};

#endif //BOT_H_

What I don't understand is the "#ifndef BOT_H_" and the "#define -- #endif"

From what I gather, it defines a constant BOT_H_ if it's not already defined when the precompiler looks at it. I don't actually get how the struct inside it is a constant and how it is going to let me access the functions inside it.

I also don't see why we're doing it this way? I used C++ a while back and I wasn't using .h files, so it might be something easy I'm missing.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jumbala
  • 4,764
  • 9
  • 45
  • 65

5 Answers5

10

This is known as an include guard, to prevent the contents of a header file from being #included more than once.

That is, it prevents the contents of the header file from being copied into the file that #includes it when it has already #included it before.

The #define isn't defining a constant for the struct, but it's simply defining a constant with no value. If that constant was previously defined, the struct will not be redeclared.

AbdullahC
  • 6,649
  • 3
  • 27
  • 43
5

It's called "include guard". It protects you from redefinitions occuring when a header is included more than once. There's also non-standard #pragma once that does the same thing, but might not be supported everywhere.

Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
3

It does not define a constant whose value is the struct. It defines a constant with an empty value.

It's there so that the content of the header is not included twice. Basically it says something like:

if (!bot_h_included)
{
    bot_h_included = true;

    // code from the header
}
svick
  • 236,525
  • 50
  • 385
  • 514
1

this is called a header guard it stops the compiler compiling or including the code more than once it is similar to pragma once

smitec
  • 3,049
  • 1
  • 16
  • 12
0

Just a side note, I don't recommend using #pragma once I see it a lot in a MVC compatible compilers but just a couple of weeks ago I was working with HP UX and the HP-CC does not support #pragma once, I strongly recommend using #ifndef/#define combinations.

lukecampbell
  • 14,728
  • 4
  • 34
  • 32
  • I recommend using both, first the pragma, then the guard. Some compilers don't optimize include guards the way they do `#pragma once` and open the header multiple times. – Xeo Nov 21 '11 at 02:17
  • @Xeo: Which? There aren't that many compilers that support `#pragma once` (GCC and MSVC, iirc); and those properly optimize header guards. – MSalters Nov 21 '11 at 07:56