Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the same variable across multiple files in C++

Tags:

c++

variables

In the process of changing some code, I have spilt some functions into multiple files. I have the files controls.cpp and display.cpp and I would like to be able to have access to the same set of variables in both files. I don't mind where they are initialized or declared, as long as the functions in both files can use them.

This was not an issue when the functions were in the same file, but now it seems almost impossible after an hour of googling and trying various things.

like image 478
Sam152 Avatar asked Mar 30 '10 11:03

Sam152


People also ask

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.

How do you use an extern variable in multiple files?

extern int globalVar; When you use extern keyword before the global variable declaration, the compiler understands you want to access a variable being defined in another program or file, and hence not to allocate any memory for this one. Instead, it simply points to the global variable defined in the other file.

How do I use extern to share variables between source files?

The clean, reliable way to declare and define global variables is to use a header file to contain an extern declaration of the variable. The header is included by the one source file that defines the variable and by all the source files that reference the variable.


1 Answers

Define the variable in one file like:

type var_name;

And declare it global in the other file like:

extern type var_name;
like image 135
codaddict Avatar answered Sep 26 '22 08:09

codaddict