|
-
July 19th, 1999, 09:03 AM
#1
Global variable
hello, i made an int variable named "My_var"
i want to acces to it from all my classes, how can i do ?
-
July 19th, 1999, 09:06 AM
#2
Re: Global variable
you'll need to extern it to every file that will use it:
in file1.cpp
int My_Var;
if file2.cpp that will use My_Var
extern int My_Var;
miked
-
July 19th, 1999, 09:08 AM
#3
Re: Global variable
Hi
Make it global, i.e. declare it outside any class in a .h file or in a dedicated .h file. Place extern int MyVar in cpp file where you need this variable. Or place this statement in a dedicated .h file. You must only be sure that you DECLARE your variable once.
HTH
Yves Le Sant
Metrology and Measurement Unit
Fundamental and Experimental Aerodynamics Departement
ONERA Meudon
(Office National d'Etudes et de Recherches Aérospatiales)
FRANCE
-
July 19th, 1999, 10:09 PM
#4
Re: Global variable
The extern keyword does not redefine the variable. It tells the compiler to look elsewhere for the variable declaration. One more item about global variables: if you have a local variable of the same name, then within that function calling that name will refer to the local variable. To access the global variable use the scope resolution operator ::. If you always use the scope resolution operator to access a global then you can easily identify globals in your code.
In file pair MyClass1.cpp/MyClass1.h:
int nMyInt; // global variable
void MyFunction()
{
int nMyInt; // local variable
nMyInt = 1; // assign 1 to local variable
::nMyInt = 2; // assign 2 to global variable
}
In file pair MyClass2.cpp/MyClass2.h:
extern int nMyInt;
-
July 20th, 1999, 01:27 AM
#5
Re: Global variable
thank you all, it's a very good help
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|