By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,194 Members | 859 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,194 IT Pros & Developers. It's quick & easy.

Extern variables and linking

P: n/a
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;
}

Jul 22 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Dave wrote in news:vs************@news.supernews.com:
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/
Jul 22 '05 #2

P: n/a
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

Jul 22 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.