-
March 29th, 2004, 08:29 PM
#1
Global Variable across multiple files?
Guys,
yet another question.
How do I use global varibales across multiple files.
and where exactly do I define the "extern int count;" ?
lets suppose I have the following
myclass.h
myclass.cpp
mymain.cpp -> this is where the main() program exists.
basically I want my class to update a global variable everytime its called, and then I want to be able to read that variable from my main as well ?
any suggestions? I m trying the "extern" but getting some LINK error saying I have unsolved external symbols.
pls help
Thanks
-
March 29th, 2004, 11:42 PM
#2
Don't use a global variable for this. Add a static member to
your class instead.
Wakeup in the morning and kick the day in the teeth!! Or something like that.
"i don't want to write leak free code or most efficient code, like others traditional (so called expert) coders do."
-
March 30th, 2004, 02:20 AM
#3
in your header declare, for example:
extern int GLOBALINT;
in your .cpp declare, for example:
int GLOBALINT = 1;
If you want to use this global variable in other classes and etc, you have to include the header file which containes: extern int GLOBALINT;
-
March 30th, 2004, 03:39 AM
#4
Exactly. And the error 'unresolved external variable' that you were receiving was because you didn't define the variable anywhere. extern keyword doesn't define a variable i.e. doesn't allocate memory for it but gives compiler a hint that the variable is defined somewhere else and it's safe to use it down in the file.
while(true)
cout<<"C++ is divine\n";
Feroz Zahid
-
March 30th, 2004, 06:50 AM
#5
Originally posted by souldog
Don't use a global variable for this. Add a static member to
your class instead.
You're right, static class member should be used. Is it me, or has there been an influx of "how do you use global variables" messages in the various C++ forums lately?
I'm asking this because usage of global variables should be discouraged. But unfortunately, it seems that others are reading very bad C++ books, reading C programming (not C++) books, or being taught by persons who really aren't good C++ programmers. I have a 100+ module library, and nowhere in there is a global variable that is shared between modules.
Regards,
Paul McKenzie
-
March 30th, 2004, 09:16 AM
#6
Global variables are a lazy programmers shortcut... As long as you don't define vast amounts of global variables you should be ok; it's not like a globally declared integer is going to cause harm
-
March 30th, 2004, 10:13 AM
#7
Mostly, agree with the words above.
But I don't like that kind of "dogmas" ("don't ever use or smth")... for each rule there can be exceptions
"UNIX is simple; it just takes a genius to understand its simplicity!"
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
|