Archived

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

static variable declaration

Recommended Posts

Iam having some problems with the static declaration!! I thought the static keyword declared a single enteity of a variable but it does not appear to do this!! Iam currently defining a variable as static in my StdAfx.h file I was under the impresion that this would create a single copy of a variable fro the entire program to use, but this does not seem to be the case, it appears that every file that includes the StdAfx.h file get there own copy of that variable the wisdom i seek is simply, how do i ensure that when i create a global variable, how can i make the entire program able to see it, but there will only be one copy??? Thanks all who try to help!! Paul. P.S. This is also the problem i am having with multithreading

Share on other sites
Mayrel    348
Static has two, incompatible, meanings in C/C++.

Inside a method or class definition, it indicates that only one instance of the declared object exists. For a class, this also means that you are able to access it without creating an instance of the class.

At the top-level, static means that the declared object is local to the source file in which it appears. What this means that is that each source file that includes StdAfx.h gets its own copy of the static variable.

What you want to do is use ''extern''. extern indicates that the declared object is defined elsewhere - so you can access the name, but the symbol is not defined in the resulting object file. Without extern, your variable would be defined in each object file, and you''d get errors to do with multiple definitions.

Inside precisely one of your source files you need to define your variable again without the extern or static specifiers. That will be the actual symbol that will make it into the program.

All your bases belong to us

Share on other sites
Shannon Barber    1681
static locks down the scope of a variable. Inside a class it locks the scope to the class - inside a file, it locks it to that file.

You want a global variable:

//In StdAfx.hextern int g_iMyInt;  //Declares a global int//In StdAfx.cppint g_iMyInt;        //Defines memory allocation for the global

Magmai Kai Holmlor
- Not For Rent