This topic is now archived and is closed to further replies.


Extern variables scope?

Recommended Posts

julienX    122
Ok I want to just make sure of this: If I declare a global extern variable in one file, will it be accesible in others? I think this is so. An example: I have 3 files: Main.cpp, Game.h, Game.cpp. If I declare a global extern in Game.cpp will I be able to modify it in the other two files? I just want to clear this up, thanks

Share this post

Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
all extern says is that the variable is declared and initialized in another file.



int g_Foo = 190;


extern int g_Foo;

I am no expert understand...but that''s the way I''ve learned it.

Share this post

Link to post
Share on other sites
Fingolfin    122
I'll just have a little rant about extern:

The whole point of using extern in this context is that it allows you to declare a global object without defining it. Global non-inline functions and global objects must only be defined once. This is a requirement that's called the one definition rule (ODR).

All objects defined in global scope without being explicitly initialised are guaranteed to have their storage

initialised to 0. So,

int i;

is equivalent to

int i = 0;

if it is defined in the global scope.

What the extern keyword is doing here is it's promising that the object is defined elsewhere in that text file or in another text file in the program. So,

extern int i;

means that somewhere else there is a definition such as

int i;

N.B. extern does not cause storage allocation to occur here. You can include it in the same file or within different files for the same program as many times as you like. Normally though, you'd use it in a public header file like Game.h and then include that in the revelant files that referred to the global object.

However if you were to explicity initialise the object with extern like this:

extern int i = 0;

and then define it again somewhere like this:

int i;

you *should* get an error as you are defining the global object more than once which breaks the ODR.

So to answer your question:

You're only allowed to define it once, but you will be able to modify it in your other two files.

[edited by - Fingolfin on March 5, 2003 10:58:52 AM]

Share this post

Link to post
Share on other sites