RSS Forums RSS
Please support our C++ advertiser: Programming Forums

external variables in a multifile program

Join Date: Apr 2004
Posts: 3,763
Reputation: Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light 
Rep Power: 17
Solved Threads: 147
Colleague
Dave Sinkula's Avatar
Dave Sinkula Dave Sinkula is offline Offline
long time no c

Re: external variables in a multifile program

  #2  
Jul 28th, 2005
Originally Posted by murschech
Does anyone have any insights to offer?
I'll try.

Originally Posted by murschech
Here's an example that doesn't work. The variable 'a' in file 1 is external (since it's defined outside of any function) so, according to the above paragraph, it should have the same value in file 2. The program, however, doesn't compile.
As it shouldn't. Identifiers need to be declared. The linkage of an identifier is a bit separate.

Originally Posted by murschech
If the line "int a" is added to file 2 it compiles and runs, giving the wrong answer 0.
I get a linker error because adding this definition conflicts with the definition in the other file.

Originally Posted by murschech
If instead the line "extern int a" is added then it runs and gives the correct answer 12. I understand why the last version works, but shouldn't the first one also (according to K&R)?
I'll borrow Chris Torek's words of wisdom: "At file scope, 'extern' means, approximately, 'read this as a declaration, not a definition'".


[aside]Using K&R1 as a reference for C++98 seems to leave room for a number of gaps.[/aside]
High Plains Blogger #plains #lounge ## I, for one, welcome our new socialist overlords.
"Capitalism is the unequal distribution of wealth. Socialism is the equal distribution of poverty."
Reply With Quote  
Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 12:31 am.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC