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.
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
In the header file write it with
extern
. And at the global scope of one of the c files declare it withoutextern
.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
and any other source files like this
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
seems to work for any type of declaration. Don't use the common keyword on #define of course.
In one header file (shared.h):
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) :
In the header file
header file
In the file with the file you want the global to live:
In the other files that need the extern version:
If you're sharing code between C and C++, remember to add the following to the
shared.h
file:You put the declaration in a header file, e.g.
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 theextern
in.