Re: extern
- From: "Me" <anti_spam_email2003@xxxxxxxxx>
- Date: 19 Jul 2005 20:36:56 -0700
Me wrote:
> DevarajA wrote:
> > Can anyone explain me what extern is used for? I thought it was used to
> > declare variables definited in other files, but i can do that also
> > without extern.
>
> I'd *highly* suggest you use the extern keyword when declaring external
> variables as opposed to just using:
>
> int a;
>
> because this looks like you're defining a global variable that gets
> zero initialized as opposed to declaring a global variable defined in
> another translation unit
>
> > /*file a.c*/
> > int a=5;
> > int main()
> > {
> > f();
> > }
> >
> > /*file b.c*/
> > int a;
> > void f()
> > {
> > printf("%d\n",a); /*it prints 5*/
> > }
Ok, I'm talking crap here based on information I vaguely remember from
something I read a long time ago (it probably had something to do with
an ancient unix compiler). What you're doing in b.c is called a
tentative definition:
6.9.2/2 "A declaration of an identifier for an object that has file
scope without an initializer, and without a storage-class specifier or
with the storage-class specifier static, constitutes a tentative
definition. If a translation unit contains one or more tentative
definitions for an identifier, and the translation unit contains no
external definition for that identifier, then the behavior is exactly
as if the translation unit contains a file scope declaration of that
identifier, with the composite type as of the end of the translation
unit, with an initializer equal to 0."
So as you can see, Jack Klein's answer was right about undefined
behavior occuring if you link these two files together because in b.c,
the compiler acts as if you have:
int a = 0;
at the very bottom.
.
- Follow-Ups:
- Re: extern
- From: DevarajA
- Re: extern
- References:
- extern
- From: DevarajA
- Re: extern
- From: Me
- extern
- Prev by Date: Re: prototypes
- Next by Date: Re: Requesting Example code: Threads and Messaging
- Previous by thread: Re: extern
- Next by thread: Re: extern
- Index(es):
Relevant Pages
|