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.
Shared Variables are a feature of the programming language APL which allows APL programs running on one processor to share information with another processor. Although originally developed for mainframe computers, Shared Variables were also used in personal computer implementations of APL.
Global variables are still global within its own process. So the answer is no, global variables are not shared between processes after a call to fork().
It should give error as we cannot declare same name variables in same storage class.
Global variables can only be shared or inherited by child processes that are forked from the parent process.
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_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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With