What are the header defines for?

M

Marco Aschwanden

I am re-learning c++. And I see lots of code. All the time I stumble
over the following pattern (in header files):

#ifndef some_filename_h
#define some_filename_h
..
..
..
#endif

What is this "filename" define good for? I found this pattern in many
examples and in many books, but it is nowhere explained what it is
good for? Can anyone explain this to me?

Thanks a lot,
Marco
 
S

Sam Holden

I am re-learning c++. And I see lots of code. All the time I stumble
over the following pattern (in header files):

#ifndef some_filename_h
#define some_filename_h
.
.
.
#endif

What is this "filename" define good for? I found this pattern in many
examples and in many books, but it is nowhere explained what it is
good for? Can anyone explain this to me?

They are include guards and are used so that a header being included
multiple times doesn't cause compilation errors (by defining something
twice, for example).
 
J

John Carson

Marco Aschwanden said:
I am re-learning c++. And I see lots of code. All the time I stumble
over the following pattern (in header files):

#ifndef some_filename_h
#define some_filename_h
.
.
.
#endif

What is this "filename" define good for? I found this pattern in many
examples and in many books, but it is nowhere explained what it is
good for? Can anyone explain this to me?

Thanks a lot,
Marco

Suppose that you #include two files, "a.h" and "b.h" into the file
"filename.cpp". Suppose that "b.h" itself #includes "a.h". That means that
"a.h" is being #included into "filename.cpp" twice: once directly and once
indirectly via "b.h". The scheme you have described stops this from
happening.

The first time "a.h" is #included, some_filename_h is not yet defined.
Accordingly

#ifndef some_filename_h

returns true, some_filename_h is then defined, and the code that follows is
read.

The second time "a.h" is #included, some_filename_h has already been
defined,

#ifndef some_filename_h

returns false and execution skips to the #endif, so none of the header code
is read.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top