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.
Global variable in C oO
Global variable in C oO
TCP/IP: Connecting people...
-
- Member
- Posts: 524
- Joined: Sun Nov 09, 2008 2:55 am
- Location: Pennsylvania, USA
Re: Global variable in C oO
AFAIK static variables don't have their symbols exported. So if in one file you wrote:
and in another file you write
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.
Code: Select all
static int foobar;
Code: Select all
extern int foobar;
EDIT: And I'm sure you could have found that with google.
Re: Global variable in C oO
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...
-
- Member
- Posts: 524
- Joined: Sun Nov 09, 2008 2:55 am
- Location: Pennsylvania, USA
Re: Global variable in C oO
Yep. The easy way of doing this is puting something like
in a standard include. Then define the global variable you want to use from multiple files like so
in (for this example) foo.h. Then in foo.c you write:
This way it will be 'extern' in all files except for foo.c.
Code: Select all
#define EXTERN extern
Code: Select all
EXTERN int foo;
Code: Select all
#undef EXTERN
#define EXTERN
#include "foo.h"
#undef EXTERN
#define EXTERN extern