View Full Version : Global variable question
If I create a global variable in one .c file, can I access this variable from another .c file?
I thought so, but I get the error "symbol 'varname' has not been defined."
Thanks,
Nathan
In one file, define it like this:
int foo;
And in the other file, define it like this:
extern int foo;
In the first file, it will define the variable, and allocate the memory space for it. In the second file, it will define the variable, but know that the memory space for it is external to that module.
jacobhurwitz
27-01-2008, 18:02
A simple way to make sure this works in all files is to add this to a header (.h) file:
#ifdef DEFINE_VARS
extern int foo;
#endif
#ifndef DEFINE_VARS
#define DEFINE_VARS
int foo;
#endif
So, what does this do? You have some macro, DEFINE_VARS. If it has already been defined, you declare extern int foo. If it hasn't been defined, you define it and declare int foo. This way, foo is external for all files but one.
I hope this helps.
vBulletin® v3.6.4, Copyright ©2000-2017, Jelsoft Enterprises Ltd.