Addresses of extern variables

Nov 4, 2009 at 10:03pm
Hi,

I've just been trying to share some data across files, and there's something I don't understand which I think might be behind some of the problems I'm having!

I have a shared header file, in which I declare, say, int foo = 5.
Then two other files which #include that header file, and both start with external declarations of foo - i.e. extern int foo.

They both report the correct value of foo, 5, but the value of &foo in each case is different. Is that expected, and if so why?

TimHe
Nov 4, 2009 at 10:38pm
No, they should have the same address. Sounds like you defined two globals with the same name in two different files.
Nov 5, 2009 at 1:19pm
When a variable is declared inside a header file (NOT externed), every .cpp file that includes that header file,
directly or indirectly, gets its own copy of that variable. You are seeing multiple addresses because you have
multiple variables with the same name.
Nov 5, 2009 at 9:22pm
Thanks for the advice. So now I've reorganised things, and I have:

DataDeclarations.h, containing 'extern int foo;'

DataDefinitions.cpp, containing 'int foo = 5;', and #include-ing DataDeclarations.h.

Two header files, myFile1.h and myFile2.h, each #include-ing DataDeclarations.h.

From myFile1.cpp and myFile2.cpp (which both #include their corresponding header files), I still get different values reported for &foo.

Have I missed the point again? :)

TimHe
Nov 6, 2009 at 12:02pm
To answer my own question: yes. I made a couple of stupid assumptions about the way I set up this project. Sorry if anyone's wasted any time on my last post, but thanks again for answers to the first one - they did help!

TimHe
Topic archived. No new replies allowed.