On Sun, Apr 11, 2010 at 4:11 AM, Otto Moerbeek <o...@drijf.net> wrote:
> On Sun, Apr 11, 2010 at 03:49:26AM -0700, James Hartley wrote:
>
>> On Sat, Apr 10, 2010 at 9:14 PM, Jesus Sanchez <zexe...@gmail.com> wrote:
>>
>> >   This is not really OpenBSD related but since it's a UNIX-like OS and
>> > here are really experienced people coding in C I thought this was a good
>> > place to ask.
>> >
>>
>> Actually, not.  Your questions are general C programming questions.  A
>> number of sites exist which thrive on questions like this.  Sometimes,
they
>> actually give the right answers.
>>
>>
>> > Back to a.c later than the 0x2211
>> > assignement I printed the variable and showed 0x11 (at that point i
>> > realized the mistake). But I was just wondering where the h*ll went the
>> > 0x22 bits on the memory??
>>
>>
>> Truncated.
>>
>>
>> >   I know the rigth thing is to declare the variable 'foo' on a header
>> > file and include it in all my code...
>>
>>
>> No, this is incorrect.  It is a poor idea to declare variables within
header
>> files.  This bad practice will lead to linker errors due to duplicate
>> definitions.
>>
>> One solution is to define all global variables in a single *.c file &
place
>> extern statements to each of these global variables in a header file which
>> can then be included as many times in as many places as you choose.  Here,
>> all global variables are defined only once which is required.
>
> You are mixing up the terms definition and declaration.
>
> In C, a declaration introduces a name and some or all properties of
> that name.
>
> A definition does the same, but also reserves memory for the object.
>
> In global scape "int a" is a definition, while "extern int a" is a
declaration.
>
> So a declaration of a variable in a header file is pefectly ok. A
> definition, hoewever, is frowned upon. There exist some rules to allow
> old code (where this idom is pretty comon) to compile and link, but
> you'd better no introduce so called "commons" in new code.
>
>        -Otto

The -fno-common option of gcc is helpful in catching this, once one
knows what to look for.

--patrick

p.s., used in compiling OP's example code gives:

b.o(.sbss+0x0): In function `overfoo':
/tmp/b.c:3: multiple definition of `foo'
a.o(.sbss+0x0):/tmp/a.c:10: first defined here
ld: Warning: size of symbol `foo' changed from 1 in a.o to 4 in b.o

Reply via email to