Accessing Global variables across files

In some projects in C, it becomes necessary to share and access global variables across file(s). In such cases, developers tend to declare the variable as global in a master source file and declare it as extern in other files. This works fine, but it is a good practice to keep all declarations in a header file. But if we keep it the declaration in a header file and include the header file in more than one file,

[code]

common.h

int gvalue;

it would result in a linker error saying gvalue has been redefined.

The work around is to use the #define macro in the header file,

[code]

common.h

#if OWNER 1
#define EXTERN
#else
#define EXTERN extern
#endif

EXTERN int gvalue;

source1.c

#define OWNER 1
#include "common.h" // gvalue is a global variable defined in source1.c
...

source2.c

#include "common.h" // gvalue is a global variable decalred as extern in source2.c
...

1 comment:

Randy said...

This is a great tip! I have put this to great utility on one of my embedded projects.