Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

extern vs. static....difference? 1

Status
Not open for further replies.

Valius

Programmer
Oct 20, 2000
174
US
I'm attempting to make a variable in one class static/extern so that I can make an instance of that class in another program and still have that data. The reason I need to do that is because when my variable goes outta scope, it looses that data....and I want it to keep the data. I've read some stuff on static and extern...I think I need to use extern but I keep getting an unresolved external symbol error (LNK2001). I'm doing something wrong, but just don't know what. Can someone please guide me in the correct direction for this info? Thanks in advance!

Niky Williams
NTS Marketing
 
Global variables are accessible (as you know) to any function defined in the same file after the variable is declared. Global variables are also accessible to functions in other files, however, the global variables must be declared in each file which they are used. For example if I define a global variable called
int flag = 1;
then in the second file I would declare
extern int flag;

Don't declare extern in both files. Only declare extern in the files that are referencing the original definition.

the extern indicates to the compiler that the variable is either defined later in the program or in another file and it is the linkers responsibility to resolve the issue. Remember to only define an object once but you can declare it several times as long as the types agree exactly (and declaration with an initializer is a definition i.e. int flag = 1;).

HTH,
JC
 
AWESOME!! Thank you SO much. I was getting my extern switched around. It works perfectly now. Thanks you SO much!

Niky Williams
NTS Marketing
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top