Re: Defining variable in C header file related doubt
- From: Jack Klein <jackklein@xxxxxxxxxxx>
- Date: Mon, 09 Jun 2008 21:57:20 -0500
On Mon, 09 Jun 2008 12:12:55 GMT, "Bartc" <bc@xxxxxxxxxx> wrote in
comp.lang.c:
"Richard Heathfield" <rjh@xxxxxxxxxxxxxxx> wrote in message
news:feKdnY5fcr2nR9HVnZ2dnUVZ8hednZ2d@xxxxxxxxx
whirlwindkevin said:
I saw a program source code in which a variable is defined in a header
file and that header file is included in 2 different C files.
And it didn't compile, obviously.
When i
compile and link the files no error is being thrown.
Then you didn't see what you thought you saw.
How is this
possible.I thought it will throw "Variable redefinition Error". Giving
the source code for reference.Please help me out on this...
a.h
-----
int g;
This is not *exactly* a definition. It's a "tentative definition"
Looks like an ordinary definition to me. What's tentative about it?
The OP's question was why, with int g declared in both files (and apparently
sharing the same space) no error was raised.
And the answer is, "C doesn't know or care."
The standard states (C99 6.9 p5):
"An external def1nition is an external declaration that is also a
definition of a function (other than an inline definition) or an
object. If an identif1er 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."
If two translation units that define the same object with external
linkage, "int g" in this case, are combined in the same program, the
rule above is broken. Since the program violates a "shall" clause
outside of a constraints section, the behavior is undefined and no
diagnostic is required.
Some tool sets will complain about this, others will not. The
behavior is undefined either way.
--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
.
- References:
- Defining variable in C header file related doubt
- From: whirlwindkevin
- Re: Defining variable in C header file related doubt
- From: Richard Heathfield
- Re: Defining variable in C header file related doubt
- From: Bartc
- Defining variable in C header file related doubt
- Prev by Date: Re: oscillator
- Next by Date: Re: How to left pad a string with spaces?
- Previous by thread: Re: Defining variable in C header file related doubt
- Next by thread: Re: Defining variable in C header file related doubt
- Index(es):
Relevant Pages
|