1

As a continuation of my previous question in stackoverflow: Getting LINK error : Extern in C++. How to access the value of a variable which is modified in File A.CPP in another file File B.CPP IN my C++ code I want to make use of a variable "VarX" in a file "B" which is actually modified in another file "A". So I had a look @ the following link & used extern concept.

How do I use extern to share variables between source files?

error LNK2001: unresolved external symbol "unsigned int VarX" (?VarX@@3IA)

My scenario is as follows:

File1.h
extern unsigned int VarX;

File2.cpp
#include File1.h
VarX = 101;

File3.cpp
#include File1.h
unsigned int temp = VarX;

IMP NOTE: In the header file File1.h there are many other structure definitions and also many othe rdefinitions apart from the Extern definition.

Can someone help me in this. How shall I read the Value of VarX which is modified in File2.cpp in another File File3.cpp.

Community
  • 1
  • 1
codeLover
  • 3,720
  • 10
  • 65
  • 121

2 Answers2

2

You should have File1.cpp with following content:

unsigned int VarX = 0;
zabulus
  • 2,373
  • 3
  • 15
  • 27
2

You have to define VarX in global scope, which I'm assuming you're not doing now, since otherwise it wouldn't even compile:

//File2.cpp
#include "File1.h"
unsigned int VarX = 101;  //this has to be outside any code block or namespace
                          //or class... 
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • Excellent. It worked. :) Thanks a lot. Stackoverflow rocks. BUt I had a query. Why is it that I need to declare VarX only in File2.cpp & how come I am not getting any such errors in File3.cpp where I am making use of this varibale "VarX" which was assigned earlier in File2.cpp. ? Can you please clear my doubt? Thanks :) – codeLover Apr 24 '12 at 14:08
  • @codeLover because that's what one definition rule means. You only define a variable **once**, in your case, `File2.cpp`. The `extern` declaration only means *"this variable is defined somewhere, you can use it."* – Luchian Grigore Apr 24 '12 at 14:10
  • Ok thank you. And I think you told me to define the variable outside of all functions, classes etc, (in global scope of File2.cpp) because, its been declared as extern in the header file & we want to make use of this definition in other files too. Thanks a lot for the info :) – codeLover Apr 24 '12 at 14:22