tags:

views:

53

answers:

2

I have a project where I need to reference a variable declared in one CPP file in another, is that possible?

If so, how?

+6  A: 

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.

LukeN
+2  A: 

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.

Brendan Long
Wasn't it the other way around?
LukeN
@LukeN: No, its not.
Georg Fritzsche
Whoops, after reading it again things cleared, sorry!
LukeN