Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Variable within Multiple Files

Tags:

c++

I have two source files that need to access a common variable. What is the best way to do this? e.g.:

source1.cpp:

int global;  int function();  int main() {     global=42;     function();     return 0; } 

source2.cpp:

int function() {     if(global==42)         return 42;     return 0; } 

Should the declaration of the variable global be static, extern, or should it be in a header file included by both files, etc?

like image 998
kaykun Avatar asked Sep 02 '10 14:09

kaykun


People also ask

How do you declare global variables in multiple files?

You should achieve that the compiler gets the same extern declaration for each compilation unit, that needs the declaration. When you spread the externs over all files that needs extern access to the variable, function, ... it is difficult to keep them in sync. That's why: don't declare extern in the consuming .

Can global variables be accessed by multiple files?

A global variable is accessible to all functions in every source file where it is declared. To avoid problems: Initialization — if a global variable is declared in more than one source file in a library, it should be initialized in only one place or you will get a compiler error.

Is it possible to use global variable in another .C file?

Every C file that wants to use a global variable declared in another file must either #include the appropriate header file or have its own declaration of the variable. Have the variable declared for real in one file only.


1 Answers

The global variable should be declared extern in a header file included by both source files, and then defined in only one of those source files:

common.h

extern int global; 

source1.cpp

#include "common.h"  int global;  int function();   int main() {     global=42;     function();     return 0; } 

source2.cpp

#include "common.h"  int function() {     if(global==42)         return 42;     return 0; } 
like image 185
e.James Avatar answered Sep 23 '22 21:09

e.James