#ifndef #define #endif and multiple definitions problem

P

prettysmurfed

Hi all

I have this, probably stupid question, how to avoid multiple
definitions when a header file is included more than once.
I thought, when you wrote the header-file and used the
ifndef/define directives, the code between the statements
define and endif was only compiled once. But this seems
to be incorrect, as I get a whole bunch of errors when
I compile the critter.
For example if I include header.h more than once the
variable foo will cause a multiple definition compile error...

#ifndef HEADER_H_
#define HEADER_H_

int foo;

#endif

When you stop laughing at my question, I would really
appreciate a solution... :)

Go steady
Martin
 
P

Peter van Merkerk

I have this, probably stupid question, how to avoid multiple
definitions when a header file is included more than once.
I thought, when you wrote the header-file and used the
ifndef/define directives, the code between the statements
define and endif was only compiled once. But this seems
to be incorrect, as I get a whole bunch of errors when
I compile the critter.
For example if I include header.h more than once the
variable foo will cause a multiple definition compile error...

#ifndef HEADER_H_
#define HEADER_H_

int foo;

#endif

Replace "int foo;" with "extern int foo;" in the header file, one
translation unit (i.e. .cpp or .cc file) should have the "int foo;"
line.
 
P

prettysmurfed

Thanks Peter
You're absolutely right... I'm not thinking straight this
morning... Far too much coffee.
 
M

MPBroida

prettysmurfed said:
Hi all

I have this, probably stupid question, how to avoid multiple
definitions when a header file is included more than once.
I thought, when you wrote the header-file and used the
ifndef/define directives, the code between the statements
define and endif was only compiled once. But this seems
to be incorrect, as I get a whole bunch of errors when
I compile the critter.
For example if I include header.h more than once the
variable foo will cause a multiple definition compile error...

#ifndef HEADER_H_
#define HEADER_H_

int foo;

#endif

When you stop laughing at my question, I would really
appreciate a solution... :)

The #ifndef/#define/#endif only prevents "int foo;"
from being compiled in one file on EACH compilation.

If you compile x.cpp separately from y.cpp, then
EACH of them will end up defining "foo". And the
linker then sees multiple definitions.

The "extern" trick is the way to avoid the problem
entirely.

Mike
 

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
474,145
Messages
2,570,826
Members
47,371
Latest member
Brkaa

Latest Threads

Top