extern variable question

Started by
4 comments, last by Shannon Barber 18 years, 7 months ago
I was going through the Pixie (renderman compliant renderer) source code. In the ri.h header file, which gets sourced by the file that contains function main(), all of the variables are declared as extern type variables. So the file that contains main is like this: #include "ri/ri.h" int main(int argc, char* argv[]) { code here; } ri.h looks like this: #ifndef RI_H #define RI_H 1 typedef char *RtToken; extern RtToken RI_FRAMEBUFFER, RI_FILE; #endif /* RI_H */ It looks like extern is being used to declare the variable. I thought that you only used extern to refer to the already-declared external variable, which you would just declare normally. For example: int test; int main(void) { extern int test; test = 1; } What happens when you declare a variable for the first time with extern?
Advertisement
An external variable is like a global variable defined in a header file, ie. a global variable that won't give you a bunch of re-definition errors. Basically, in a header file, you have the extern declaration, like extern int x;, then in one source file, you have the definition, int x;. That way, all files that include that specific header file can access x without redefinition.
Free speech for the living, dead men tell no tales,Your laughing finger will never point again...Omerta!Sing for me now!
extern is used to declare (specify its type) a variable that is defined (instantiated) somewhere else.

"extern RtToken RI_FRAMEBUFFER, RI_FILE;" means that RI_FRAMEBUFFER and RI_FILE are objects of type RtToken and are defined somewhere else.
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!
OK,

So you'd have something like this:

In globals.h:

extern int test; /* declare the extern variable */

in file 1:
int test = 1; /* define the extern variable */


in file 2:
#include "globals.h"

if (test == 1) /* access the extern variable without explicitly re-declaring it */
{
/* do stuff */
}


Is that right?
that is right. You have to have exactly one declaration of the variable and extern statements in all other files.
It's good practice to define the variable as extern as well.
If it's a global, it should always be declared extern.

//header
extern int ImHere;

//source
extern int ImHere = 0;

And if it's not extern, it should be static.
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara

This topic is closed to new replies.

Advertisement