cfiles between sharing shared global variables in C
In one header file (shared.h):
extern int this_is_global;
In every file that you want to use this global symbol, include header containing the extern declaration:
To avoid multiple linker definitions, just one declaration of your global symbol must be present across your compilation units (e.g: shared.cpp) :
/* shared.cpp */ #include "shared.h" int this_is_global;
How can I create global variables that are shared in C? If I put it in a header file, then the linker complains that the variables are already defined. Is the only way to declare the variable in one of my C files and to manually put in
externs at the top of all the other C files that want to use it? That sounds not ideal.
You put the declaration in a header file, e.g.
extern int my_global;
In one of your .c files you define it at global scope.
Every .c file that wants access to
my_global includes the header file with the
There is a cleaner way with just one header file so it is simpler to maintain. In the header with the global variables prefix each declaration with a keyword (I use common) then in just one source file include it like this
#define common #include "globals.h" #undef common
and any other source files like this
#define common extern #include "globals.h" #undef common
Just make sure you don't initialise any of the variables in the globals.h file or the linker will still complain as an initialised variable is not treated as external even with the extern keyword. The global.h file looks similar to this
#pragma once common int globala; common int globalb; etc.
seems to work for any type of declaration. Don't use the common keyword on #define of course.