Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Extern variables and linking

Reply
Thread Tools

Extern variables and linking

 
 
Dave
Guest
Posts: n/a
 
      12-02-2003
Why does the program below link successfully? (Yep, what's shown is all
there is to it.) Does an extern variable actually have to be referenced to
be bound to an address? Is this Standard-compliant behavior?


int main()
{
extern int a;
}



 
Reply With Quote
 
 
 
 
Rob Williscroft
Guest
Posts: n/a
 
      12-02-2003
Dave wrote in news:(E-Mail Removed):

> Why does the program below link successfully? (Yep, what's shown is
> all there is to it.) Does an extern variable actually have to be
> referenced to be bound to an address?


Sorry that last sentence just doesn't parse.

> Is this Standard-compliant behavior?


Yes.

>
>
> int main()
> {
> extern int a;


You're telling the compiler such an object 'a' exists, but since you
*never* reference it the compiler never uses the information. If this
wern't the case including headers would link huge amounts of unused
code and data (just so the optimizer can throw it all away again .

Try adding:

a = 1;

> }
>


Rob.
--
http://www.victim-prime.dsl.pipex.com/
 
Reply With Quote
 
 
 
 
E. Robert Tisdale
Guest
Posts: n/a
 
      12-02-2003
Dave wrote:

> Why does the program below link successfully?
> (Yep, what's shown is all there is to it.)
> Does an extern variable actually have to be referenced
> to be bound to an address?
> Is this Standard-compliant behavior?
>
> int main() {
> extern int a;
> }



> cat main.c

int main(int argc, char* argv[]) {
extern int a;
return 0;
}

> g++ -Wall -ansi -pedantic -c main.c

main.c: In function `int main(int, char**)':
main.c:2: warning: unused variable `int a'
> nm main.o

00000000 T main



> cat main.c

int main(int argc, char* argv[]) {
extern int a;
return a;
}

> g++ -Wall -ansi -pedantic -c main.c
> nm main.o

U a
00000000 T main

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Difference of extern short *x and extern short x[]? Andre C Programming 5 07-17-2012 07:38 PM
linking problem? | extern keyword Stanley Rice C Programming 6 11-15-2011 11:50 AM
Embedded python adding variables linking to C++-Variables / callbacks iwl Python 3 12-07-2006 08:54 PM
extern var's and linking Bill Nolan C++ 1 12-30-2004 05:16 PM
extern const char * vs. extern const char []http://tinyurl.com/47e3k Thomas Matthews C++ 5 08-02-2004 10:36 AM



Advertisments