| re: #ifndef #define #endif and multiple definitions problem
prettysmurfed wrote:[color=blue]
>
> 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... :-)[/color]
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 |