James Kuyper
6/18/2011 2:34:00 PM
On 06/18/2011 08:51 AM, Mark wrote:
> Hi,
>
> "China Blue Angels" <chine.bleu@yahoo.com> wrote in message
> news:chine.bleu-D062AE.20523717062011@news.eternal-september.org...
....
>> You shouldn't define the same external name with different types in
>> different
>> source files, but not all compilers and loaders will catch this.
>>
>
> Could you elaborate on this statement, what can go wrong ? What does the
> standard say about such case?
6.9p5:
> ... If an identifier declared with external
> linkage is used in an expression (other than as part of the operand of a sizeof operator
> whose result is an integer constant), somewhere in the entire program there shall be
> exactly one external definition for the identifier; otherwise, there shall be no more than
> one.
Those "shall"s occur outside of a constraint section. Code which
violates them therefore has undefined behavior (4p2). That means that
the C standard imposes no requirements on what the implementation does
with your code. In principle, that means that just about anything can
happen.
In practice, if the linker even accepts such code, one common
possibility is that both definitions will share overlapping pieces of
memory, as if they were in a union with each other. Another possibility
is that they are stored in completely different pieces of memory. A
third possibility is that they are assigned to a piece of memory that's
only big enough to store the smaller type, and that any attempt to read
or write using the definition with the larger type will attempt to
access memory allocated for some other use, generally with catastrophic
consequences.
> So, if I understand you correctly, this should not happen:
More precisely, this should not be done. It can quite easily happen.
> a.h:
> extern int x;
>
> a.c:
> #include "a.h"
> int x;
>
> b.h:
> extern long x;
>
> b.c:
> #include "b.h"
> long x;
>
> So If later I link both object files a.o and b.o into target exeecutable,
> and if linker can't catch this, it's possible that compiler may generate
> code so that long vale will be assigned to integer object?
That's among the least likely of the possibilities, but it is also
technically possible.
--
James Kuyper