I have a project where I need to reference a variable declared in one CPP file in another, is that possible?
If so, how?
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.
Create a .h file declaring the variable you need as extern
(something like extern int X;
), then include it in any file that need that variable. In one of the .cpp files you're linking, declare it without the extern
.