I have defined a variable locally to a function in C++, but would like to have it accessible to another C++ function contained in a separate file.
In R, <<- allows local variables to be accessed globally by copying it.
Is there an equivalent to <<- in C++ that will allow me to call local variables (that otherwise is not defined globally) via the extern declaration in another C++ file?
Would the code below be OK and work as expected?
For example, to access y:
### File 1.cpp ###
void func() {
const std::vector x
int y = x.size()
}
### File 2.cpp ###
extern int y
y // Call y somewhere else within program
In C++, a function cannot leak declarations into enclosing scopes. The closest thing you can do is this:
void f() {
extern int x;
}
This causes x
to refer to a global variable that is defined somewhere else in the program. Another function in another translation unit, containing the same declaration, could then refer to the same variable. However, neither declaration defines the variable, and you must supply a definition at global scope in order for the program to link.
If it's a global variable you need, you should define a global variable. However, mutable global state often makes programs harder to reason about, so it's usually better to avoid it whenever possible. Typically, you'll want to structure your program so that two functions communicate with each other through the function call mechanism whenever possible (passing information in function parameters), or, at worst, share mutable state encapsulated inside a class, so that it can't leak outside the class.