|
-
May 19th, 1999, 10:29 AM
#1
where can I declare a global variable
I want to declare a global variable, one that all classes that I
ever create in a single program will have as a declared variable.
Unfortunately if I declare 'int g_var;' at the top of the view
or doc class, other classes that I create don't recognize it
even if I put the #include <view> at the top of the class.
The question is, how can I declare a global variable?
-
May 19th, 1999, 10:50 AM
#2
Re: where can I declare a global variable
If you're sticking to classes, forget about global variables because object oriented disciplines forbade that. Alternatively, you can consider creating friend classes or static member variables and functions for kind of 'global' access.
-
May 19th, 1999, 05:09 PM
#3
Re: where can I declare a global variable
You can't really declare a truly global variable, but you can link the same variable amoung several different source files with the 'extern' keyword.
// You need to declare this in each file
// where you want to use g_var
extern int g_var;
Good Luck,
John
-
May 20th, 1999, 03:46 AM
#4
Re: where can I declare a global variable
you must declare
extern my_type my_var;
in your header which is included in all the files (global.h)
but you must also declare
my_type my_var;
in the corresponding cpp file (global.cpp)
good luck
###
#####
#######
#####
\\\|/// ###
| ~ ~ | #
(- * * -) #
------------oOOo-(_)-oO#o-----------
| #
^ #
" #
##
-
May 20th, 1999, 05:53 AM
#5
Re: where can I declare a global variable
You can follow the suggestions already given, but it is considered poor technique to use global variables if there is an alternative, because of the global namespace pollution implications (amongst other things).
One alternative to consider is to put them into your CWinApp-derived class. The application is a legitimate global instance defined in the CWinApp-derived class source file, and called 'theApp'. If you put 'extern CMyWinApp theApp;'
in the source files where you need to access these variables, you can access them via 'theApp', e.g. int var1 = theApp.GetVar1();
Alternatively, you could put them into a suitably named namespace, use them like globals, but with 'using' declarations or explicit prefixes.
Dave
-
June 6th, 1999, 01:09 AM
#6
Re: where can I declare a global variable
could be the brackets <> instead of "" in the include statement
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
|