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.

Great, thanks!

Nathan

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.