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.
views:
114answers:
4
+10
A:
in the header file write it with extern. And in one of the c files declare it without extern.
dig
2010-06-09 23:16:14
+6
A:
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;
Hernán
2010-06-09 23:18:32
+2
A:
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.
nos
2010-06-09 23:19:15
+1
A:
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"
jim mcnamara
2010-06-09 23:25:16
Good approach using the preprocessor.
Hernán
2010-06-09 23:29:37
ah 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
Claudiu
2010-06-10 04:03:57