Game Development Community

Extern variables

by Rob Segal · in Torque Game Engine · 08/14/2001 (3:04 pm) · 3 replies

Looking over the code and trying to remember what the "extern" keyword actually means when used to
define a variable.

If you define a variable in a header file and then include that header file in a c++ source file can you not
access that variable as if it were in the c++ source file?

So why am I getting errors when trying to compile a nice little program that wants to access the variable
"winState" which is defined in platform/platformWin32.h ? Any ideas

#1
08/14/2001 (4:41 pm)
An EXTERN variable is declared somewhere OUTSIDE the code block you're working in... for example, GAME.CC declares (making this up) int g_iCounter = 123;. Later, in player.cc I could access that global by putting EXTERN int g_iCounter; This would allow me to access the variable declared in game.cc without including the header file from game.cc

It's basically saying "yeah, I know it's not declared anywhere here. I'll make it somewhere else, and you can access it once it's linked to the other module"

-bw
#2
08/15/2001 (12:52 pm)
Extern is a keyword used in C++ for global variables.

It tells the compiler that the variable is defined in another file so no to spit out errors about undefined variables. It also clears up file scoping issues.

if in blah.cpp I declared a global variable:
int blah;
I'd only be able to use that variable in any function in blah.cpp.

Now:
in file fu.cpp i also create a global variable named:
int blah;
this variable would have file scope to fu.cpp and all it's functions.

now if I want to share "blah" with all functions between the two files blah.cpp and fu.cpp I'd place "extern" keyword in front of one of the deffinitions. probably in fu.cpp. so it'd look like this

blah.cpp:
int blah;
// code and stuff

fu.cpp:
extern int blah;
// code and stuff
#3
08/15/2001 (4:22 pm)
Thanks to all those who have replied and indeed I have finally gotten my program to work. One note
however. In my case the extern variable I wanted to access had a structure as its type which also
had a constructor defined in its definition. I had to define this constructor in the file I was using the
variable in before I could get a clean compilation.

So, for example:

in foo.cpp:

struct Vector {
float x, y, z;

Vector();
}

extern Vector x;

and then in bar.cpp

Vector x;

Vector::Vector() {
x = y =z = 0;
}

This is the only way it seemed to work.