Click to See Complete Forum and Search --> : where can I declare a global variable
Danielle Harvey
May 19th, 1999, 10:29 AM
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?
Syelixn
May 19th, 1999, 10:50 AM
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.
John Holifield
May 19th, 1999, 05:09 PM
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
polo
May 20th, 1999, 03:46 AM
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-----------
| #
^ #
" #
##
Dave Lorde
May 20th, 1999, 05:53 AM
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
Sergio Acosta
June 6th, 1999, 01:09 AM
could be the brackets <> instead of "" in the include statement
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.