Re: multiple definitions....
- From: Lew Pitcher <lpitcher@xxxxxxxxxxxx>
- Date: Thu, 16 Jun 2005 20:41:24 -0400
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
lbj137@xxxxxxxxx wrote:
> I have two files: A.c and B.c. In both files I define a global
> variable, int xxxx; When I compile with a green hills compiler (and
> also i think with a GNU compiler) I get no errors or warnings. Only
> when I initialize xxxx to two different values in A.c and B.c
> respectively do I get a 'multiple definitions' error. I was under the
> impression that I would get such an error even without initializing
> xxxx twice, simply because i am (ostensibly) allocating memory for it
> twice. what is going on here?
While this is not strictly a C issue (at least I don't think it is), and thus
is off topic here, I think that a short explanation might help.
Compilers can be smart. If they see that a global is allocated but not
initialized, they can just make space for it in their map of where data is
stored, but not actually generate the instructions/data to fill in the space.
When a global is allocated by more than one translation unit, the linker (or
what ever performs that task) can attempt to resolve the 'space left for the
global' into a usable (load image, execution image, 'core' ) form.
When both tu initialize the global, the linker can't decide which
initialization to use, and you get a multiple definition error.
When only one tu initializes the global, the linker uses that tu's allocation,
and fills in the blanks into the tu that didn't initialize the global.
When neither tu initialize the global, the linker allocates it directly, and
fills in the blanks in both of the tu's.
In other words, you can allocate a global in multpile translation units, but
you are only permitted to give it an initial value in one of those TUs.
- --
Lew Pitcher
Master Codewright & JOAT-in-training | GPG public key available on request
Registered Linux User #112576 (http://counter.li.org/)
Slackware - Because I know what I'm doing.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)
iD8DBQFCshw0agVFX4UWr64RAtdeAJ9GRAARlW4hIHJmCr3JBWVmacGRFACbBPVp
dJ46PHXfhoXTfNx4KEjSXmM=
=z5/3
-----END PGP SIGNATURE-----
.
- Follow-Ups:
- Re: multiple definitions....
- From: Jean-Claude Arbaut
- Re: multiple definitions....
- References:
- multiple definitions....
- From: lbj137
- multiple definitions....
- Prev by Date: Implement set for generate data type?
- Next by Date: Re: Implement set for generate data type?
- Previous by thread: multiple definitions....
- Next by thread: Re: multiple definitions....
- Index(es):
Relevant Pages
|