I know one should not use global variables but I have a need for them. I have read that any variable declared outside a function is a global variable. I have done so, but in another *.cpp
file, that variable could not be found. So it was not really global. Isn't it so that one has to create a header file GlobalVariabels.h
and include that file to any other *cpp
file that uses it?
The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.
The C language allows the redeclaration of the global variable. It means that this variable can get declared again when the first declaration doesn't lead to the initialization of the variable. It is possible because the second program works pretty well in the C language even if the first one fails during compilation.
Global variables are defined outside a function, usually on top of the program. Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program.
I have read that any variable declared outside a function is a global variable. I have done so, but in another *.cpp File that variable could not be found. So it was not realy global.
According to the concept of scope, your variable is global. However, what you've read/understood is overly-simplified.
Perhaps you forgot to declare the variable in the other translation unit (TU). Here's an example:
int x = 5; // declaration and definition of my global variable
// I want to use `x` here, too. // But I need b.cpp to know that it exists, first: extern int x; // declaration (not definition) void foo() { cout << x; // OK }
Typically you'd place extern int x;
in a header file that gets included into b.cpp, and also into any other TU that ends up needing to use x
.
Additionally, it's possible that the variable has internal linkage, meaning that it's not exposed across translation units. This will be the case by default if the variable is marked const
([C++11: 3.5/3]
):
const int x = 5; // file-`static` by default, because `const`
extern const int x; // says there's a `x` that we can use somewhere... void foo() { cout << x; // ... but actually there isn't. So, linker error. }
You could fix this by applying extern
to the definition, too:
extern const int x = 5;
This whole malarky is roughly equivalent to the mess you go through making functions visible/usable across TU boundaries, but with some differences in how you go about it.
You declare the variable as extern
in a common header:
//globals.h extern int x;
And define it in an implementation file.
//globals.cpp int x = 1337;
You can then include the header everywhere you need access to it.
I suggest you also wrap the variable inside a namespace
.
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