shared global variables in C
Solution 1
In the header file write it with extern
.
And at the global scope of one of the c files declare it without extern
.
Solution 2
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:
#include "shared.h"
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;
Solution 3
In the header file
header file
#ifndef SHAREFILE_INCLUDED
#define SHAREFILE_INCLUDED
#ifdef MAIN_FILE
int global;
#else
extern int global;
#endif
#endif
In the file with the file you want the global to live:
#define MAIN_FILE
#include "share.h"
In the other files that need the extern version:
#include "share.h"
Solution 4
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.
int my_global;
Every .c file that wants access to my_global
includes the header file with the extern
in.
Solution 5
If you're sharing code between C and C++, remember to add the following to the shared.h
file:
#ifdef __cplusplus
extern "C" {
#endif
extern int my_global;
/* other extern declarations ... */
#ifdef __cplusplus
}
#endif
Claudiu
Graduated from Brown University. E-mail: [email protected]
Updated on July 08, 2022Comments
-
Claudiu almost 2 years
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
extern
s at the top of all the other C files that want to use it? That sounds not ideal. -
Claudiu almost 14 yearsah this is the solution i had a while ago - i forgot about the MAIN_FILE preprocessor variable. i thinik i like the cur accepted answer more tho
-
NickO over 11 yearsdo you have any preferred references to learn more about IPC mechanisms?
-
AntonioCS over 10 yearsPlease put more emphasis on "just one declaration of your global symbol..." Kind of tripped on that one. I had the declaration on all the c files I wanted to use the global variables on :(
-
Geremia over 8 yearsCan we declare it in that *.c file's header file instead?
-
GDavid over 2 yearsYou can also add
#ifndef common
#define common extern
#endif
to the header if you want to avoid defining common every time globals.h is included. The only caveat is that common is not undefined automatically.