I have a global variable in one of the cpp files, where I am assigning a value to it. Now in order to be able to use it in another cpp file, I am declaring it as extern
and this file has multiple functions that use it so I am doing this globally. Now the value of this variable can be accessed in one of the functions and not in the other one. Any suggestions except using it in a header file would be good because I wasted 4 days playing with that.
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.
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.
External variables are also known as global variables. These variables are defined outside the function. These variables are available globally throughout the function execution. The value of global variables can be modified by the functions.
Sorry, I'm ignoring the request for answers suggesting anything other than the use of header files. This is what headers are for, when you use them correctly... Read carefully:
global.h
#ifndef MY_GLOBALS_H #define MY_GLOBALS_H // This is a declaration of your variable, which tells the linker this value // is found elsewhere. Anyone who wishes to use it must include global.h, // either directly or indirectly. extern int myglobalint; #endif
global.cpp
#include "global.h" // This is the definition of your variable. It can only happen in one place. // You must include global.h so that the compiler matches it to the correct // one, and doesn't implicitly convert it to static. int myglobalint = 0;
user.cpp
// Anyone who uses the global value must include the appropriate header. #include "global.h" void SomeFunction() { // Now you can access the variable. int temp = myglobalint; }
Now, when you compile and link your project, you must:
Using the syntax I have given above, you should have neither compile nor link errors.
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