Alex Rivera | Logout

shared global variables in C

Asked 2010-06-09T23:12:57.307
90

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.

Edit
Report

3 Answers

100

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;
answered 2010-06-09T23:18:32.887
71

In the header file write it with extern. And at the global scope of one of the c files declare it without extern.

answered 2010-06-09T23:16:14.803
6

If you're sharing code between C and C++, remember to add the following to the shared.hfile:

#ifdef __cplusplus
extern "C" {
#endif

extern int my_global;
/* other extern declarations ... */

#ifdef __cplusplus
}
#endif
answered 2013-06-06T13:52:45.690

Your Answer