Archived

This topic is now archived and is closed to further replies.

Globals not recognized

This topic is 5151 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I declare globals in my main.cpp file, and try to use them in a utility.cpp file, yet the utility.cpp file doesn''t recognize the globals existence. If I put the globals into a main.h and include the main.h within the utility.cpp or the utility.h, then I get an error when it links the objects saying that those global things exist in two objects, and it cannot link. What can I do to make it so my globals can be safely used by everything?

Share this post


Link to post
Share on other sites


Globals.h
/ | \
/ | \
/ | \
A.cpp B.cpp C.cpp



Say you want an integer called Number that you want to be able to use in all 3 CPP files. You type this in the Globals.h -

extern int Number;

and this in ANY ONE of the cpp files:
int Number;


Now that var will be shared across all 3 CPP files. Saying extern in the header file tells your compiler that that specific variable is going to be used globally in the project, and then when you declare that same int in any one of the cpp files you''re actually saying that it''s there. Now that same var will be used in all cpp files.

Share this post


Link to post
Share on other sites
Use the 'extern' keyword. What it does is it tells the compiler that that variable is already defined in another compiler unit (.cpp file) and that you should create it again. Here's an example:

// test2.cpp

extern int var1;
extern int var2;

void func()
{
var1=0;
}

// test.cpp

// only declare these in one cpp

int var1=1;
int var2=2;

It's generally a very bad idea to use globals (and singeltons-because they promote global access, however, if you pass the singelton to the functions instead of using it directly it's ok). Globals can make your code very hard to maintain and even harder to re-use it (whether it is object oriented or uses functions).
EDIT: darn, too late

[edited by - brassfish89 on November 8, 2003 11:43:52 AM]

Share this post


Link to post
Share on other sites