Post by scotthi, sorry if this has been adressed some where elss. if it has plz can
you point me to it and ill go read it.
any way, i want to declare some variables with in a header file. lets
say int i;
i then want to be able to acess that variable from multipul .cpp files
where I can read it and also change the value. i would like to hold it
in a struct or a class eventualy but i can't even get it to work on its
own at min, so i thought id start off simple and ask how i do it just
like what i described above.
any help would be grate,
thx scott
A C++ program is a collection of ".cpp" files and nothing more.
When you compile a C++ program, you supply the compiler with the ".cpp"
files, for example:
g++ monkey.cpp cow.cpp orange.cpp
The compiler will create an executable for you.
The "monkey.cpp" can use functions and global variables defined in the two
other files, "cow.cpp" and "orange.cpp", and vice versa.
So let's say in "cow.cpp", you have a global variable as so:
//cow.cpp
int cow = 7;
Now, while "monkey.cpp" is being compiled, the compiler comes across:
//monkey.cpp
int main()
{
cow += 6;
}
But... the problem here is that "monkey.cpp" hasn't got a clue about the
variable "cow". To remedy the situation, if you were to do:
//monkey.cpp
int cow;
int main()
{
cow += 6;
}
Then there would be no problem at all with "monkey.cpp", but then when the
compiler goes to compile the three files together it will say:
ERROR: Multiple Definitions
So... what you want is a declaration, which says: "Don't actually create
(define) a variable, all I want to do is let you know about one that already
exists". You do this as follows:
//monkey.cpp
extern int cow;
int main()
{
cow +=4;
}
//cow.cpp
int cow;
Now when you compile "monkey.cpp" and "cow.cpp" together, everything will be
perfect.
But...
if you compile "monkey.cpp" on its own, there will be an error - you access
the variable "cow", so there must be a definition of it.
So... in summation...
If you want to have a global variable and give other .cpp files access to it
via a header file, this is how it's done:
//blah.hpp
extern int blah;
//blah.cpp
int blah = 5;
Then all the other .cpp files have to do is include "blah.hpp". And one more
thing... when they're compiling their program, they've to put in "blah.cpp"
with it aswell, for example:
g++ myfile.cpp blah.cpp
One more thing:
When you put the following in a ".cpp" file:
#include "blah.hpp"
What happens is that the exact contents of the header file get copy-and-
pasted into where the #include line was.
And one more little thing: Google for "inclusion guards".
-JKop