Extern variables and linking

D

Dave

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;
}
 
R

Rob Williscroft

Dave wrote in
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.
 
E

E. Robert Tisdale

Dave said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top