Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shared global variables in C

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.

like image 612
Claudiu Avatar asked Jun 09 '10 23:06

Claudiu


People also ask

What is a shared variable in C?

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.

Are global variables shared between processes in C?

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().

Can 2 global variable have same name?

It should give error as we cannot declare same name variables in same storage class.

Can global variables be shared between processes?

Global variables can only be shared or inherited by child processes that are forked from the parent process.


3 Answers

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;
like image 189
Hernán Avatar answered Oct 16 '22 02:10

Hernán


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

like image 35
Dig Avatar answered Oct 16 '22 02:10

Dig


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"
like image 22
jim mcnamara Avatar answered Oct 16 '22 02:10

jim mcnamara