shared global variables in C shared global variables in C c c

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:

#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;


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


In the header file

header file

#ifndef SHAREFILE_INCLUDED#define SHAREFILE_INCLUDED#ifdef  MAIN_FILEint global;#elseextern 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"