Sign in to follow this  
mjs1

extern variable question

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
that is right. You have to have exactly one declaration of the variable and extern statements in all other files.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this