* vkp:
Thanks V, but could you please elaborate? So is there a limit on how
many times a file can be included in other files? why would it say
multiple definition, we are just including the file, we are not
redefining the variables of included file. As I said I'm beginner and
am curious to know this.
When you have two files [a.cpp] and [b.cpp] and compile them separately, each
file's code may, for example, use an ordinary[1] variable called 'x', declared
outside any routine or class.
If 'x' has internal linkage (as it has with keyword 'static', and also by
default if it's 'const') then the 'x' in [a.cpp] is a different variable than
the one in [b.cpp].
If 'x' has external linkage then both names, in [a.cpp] and [b.cpp], refer to
the same variable, and must be declared with the same type.
And then, for the compiler (or more precisely the linker), there is the problem
of deciding whether e.g. the declaration of 'x' in [b.cpp] is an error, an
inadvertent use of the same name as in [a.cpp], or whether it's intentional,
meant to refer to the same variable as in [a.cpp].
Different languages solve that problem in different ways, and indeed C and C++
solve it in different ways.
In C++ there can and must be only 1 actual *definition* of 'x', e.g. in [a.cpp],
and the other declarations, e.g. in [b.cpp], must be pure declarations,
declarations that don't define the variable but just refer to it. When you don't
use 'extern' you have a definition, and also when you provide an explicit
initialization you have a definition. When you use 'extern' and don't provide
any explicit initialization, you have a pure declaration.
Cheers & hth.,
- Alf