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

external variables in a multifile program

Join Date: Dec 2004
Location: Allentown, PA
Posts: 60
Reputation: murschech is an unknown quantity at this point 
Rep Power: 4
Solved Threads: 1
murschech murschech is offline Offline
Junior Poster in Training

external variables in a multifile program

  #1  
Jul 28th, 2005
I have a question on external variables in a multifile program.
Quoting from K&R (first addition, page 72)

"By default, external variables are also "global", so that all references to such a variable by the same name (even from functions compiled separately) are references to the same thing."

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. If the line "int a" is added to
file 2 it compiles and runs, giving the wrong answer 0. 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)?

Does anyone have any insights to offer?

_____________________file 1____________________________
#include <iostream>
using namespace std;

int a=6;
int f(int);
main()
{   cout << f(2) << endl;
}
________________file 2____________________________
int f(int x)
{   return (a*x);
}
AddThis Social Bookmark Button
Reply With Quote  
Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 11:57 pm.
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