Jump to content
  • Advertisement
Sign in to follow this  
mjs1

extern variable question

This topic is 4678 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
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.

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!