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.
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.
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.
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.
Define the variable in one file like:
type var_name;
And declare it global in the other file like:
extern type var_name;
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