I have a project where I need to reference a variable declared in one CPP file in another, is that possible?
If so, how?
It is possible, if you declare it as global (top-level, above any function definition) and use "extern ;" in other files to make it known to the compiler.
// Main.cpp
#include <...>
int myNum;
int main(int argc, char** argv)
{
// MAGIC BE HERE
return 0;
}
and
// Second.cpp
#include <...>
extern int myNum;
int f()
{
return myNum * 2;
}
extern prevents the compiler from allocating memory again when a variable was allocated in another file.
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