Let's imagine I have a header file like so:
// foo.h struct Foo { };
And then I accidentally include it twice:
#include "foo.h" #include "foo.h"
This would end up attempting to compile the following, which would generate an error...
struct Foo { }; struct Foo //< error 'Foo' declared twice { };
One way to fix this is to get the pre-processor to remove the second occurance, and to do this we define a unique identifer per header file. e.g.
#ifndef FOO_H_ #define FOO_H_ struct Foo { }; #endif
And now if we accidentally include it twice...
#ifndef FOO_H_ //< not yet declared #define FOO_H_ //< so declare it struct Foo { }; #endif #ifndef FOO_H_ //< this time FOO_H is defined... #define FOO_H_ //< ... so DO NOT include this code. struct Foo { }; #endif
Personally though I'd recommend achieving this same thing via the slighty non-standard (although supported by most, if not all, compilers).
#pragma once //< only ever include this file once struct Foo { };