Reputation: 30276
When I create header file in Microsoft Visual Studio, it's just a blank file, and I often add some prototype of function or class etc...
When I create header file from Netbean. It's often has this structure. (Assume my header file is example):
#ifndef EXAMPLE_H
#define EXAMPLE_H
// put code here
#endif
Please tell me, meaning of those bunch of codes above. If I delete this, are there any problem ? I feel strange because VS doesn't generate this.
Thanks :)
Upvotes: 1
Views: 392
Reputation: 13160
These are called include guards, they prevent multiple definition errors when you include the same file multiple times. Even if you don't, they don't hurt anybody, so you might as well leave them in.
How it works is, it checks if the macro EXAMPLE_H
is defined. If it is, it leaves out the entire file. If it isn't, it defines it, and keeps the file. That way, the next time this file appears the contents are left out.
This often happens if you have two different headers that include the same header, such as:
a.h
#ifndef A_H
#define A_H
struct Foo {};
#endif
b.h
#include "a.h"
#ifndef B_H
#define B_H
struct Bar
{
Foo x;
};
#endif
c.h
#include "a.h"
#ifndef C_H
#define C_H
struct Baz
{
Foo f;
};
#endif
And then you create stuff.cpp with
#include "b.h"
#include "c.h"
Bar y;
Baz z;
after preprocessing stuff.cpp will have
struct Foo {};
struct Bar
{
Foo x;
};
struct Baz
{
Foo f;
};
Bar y;
Baz z;
as opposed to (without include guards)
struct Foo {};
struct Bar
{
Foo x;
};
struct Foo {};
struct Baz
{
Foo f;
};
Bar y
which will give you an error about multiple definitions of Foo
.
Upvotes: 3
Reputation: 48096
Those lines ensure that the file is only included once. They prevent linking errors that occur when you include a .h in multiple files.
Upvotes: 0