Page 1 of 1

Global variable in C oO

Posted: Sun Jan 18, 2009 12:07 am
by skwee
Hello people!
I hate globals (and this is probably the reason I like C++), but I need them. I know that if I want function not to be accessible outside of .C file, I would declare it static, what about variable? Variable declared either static or not in .C file wont be accessible outside of the file, But what the real difference between global static and non-static (and please don't tell me to go learn C or something else, I know what is static, I never used it as a global variable).

Thanks.

Re: Global variable in C oO

Posted: Sun Jan 18, 2009 12:11 am
by JohnnyTheDon
AFAIK static variables don't have their symbols exported. So if in one file you wrote:

Code: Select all

static int foobar;
and in another file you write

Code: Select all

extern int foobar;
there will be an unresolved external. I use it to help prevent name clashes with global variables only used in one file.

EDIT: And I'm sure you could have found that with google.

Re: Global variable in C oO

Posted: Sun Jan 18, 2009 12:13 am
by skwee
So actually if you declare a global variable named foo in .C file and I know its name is foo so I can in my file write "extern foo" and I get access to it?

Re: Global variable in C oO

Posted: Sun Jan 18, 2009 12:23 am
by JohnnyTheDon
Yep. The easy way of doing this is puting something like

Code: Select all

#define EXTERN extern
in a standard include. Then define the global variable you want to use from multiple files like so

Code: Select all

EXTERN int foo;
in (for this example) foo.h. Then in foo.c you write:

Code: Select all

#undef EXTERN
#define EXTERN
#include "foo.h"
#undef EXTERN
#define EXTERN extern
This way it will be 'extern' in all files except for foo.c.

Re: Global variable in C oO

Posted: Sun Jan 18, 2009 4:59 am
by skwee
Thanks :)