Global variable in C oO

Programming, for all ages and all languages.
Post Reply
User avatar
skwee
Member
Member
Posts: 73
Joined: Mon Jan 12, 2009 3:11 am

Global variable in C oO

Post 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.
TCP/IP: Connecting people...
JohnnyTheDon
Member
Member
Posts: 524
Joined: Sun Nov 09, 2008 2:55 am
Location: Pennsylvania, USA

Re: Global variable in C oO

Post 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.
User avatar
skwee
Member
Member
Posts: 73
Joined: Mon Jan 12, 2009 3:11 am

Re: Global variable in C oO

Post 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?
TCP/IP: Connecting people...
JohnnyTheDon
Member
Member
Posts: 524
Joined: Sun Nov 09, 2008 2:55 am
Location: Pennsylvania, USA

Re: Global variable in C oO

Post 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.
User avatar
skwee
Member
Member
Posts: 73
Joined: Mon Jan 12, 2009 3:11 am

Re: Global variable in C oO

Post by skwee »

Thanks :)
TCP/IP: Connecting people...
Post Reply