views:

126

answers:

4

Hi,

I have a set of global variables and a method in a cpp file.

int a;

int b;

int c;

void DoStuff()
{

}

in the header file I have declared them explicitly with the extern keyword. My problem is when I include the header file in another C++ file, I can't use the external variables and the method. It's giving a linker error saying error LNK2001: unresolved external symbol for the methods and variables. What have I done wrong here??

PS: DoStuff() method populates the variables. All the header files and cpp files are in the same project folder.

Thank You!

+2  A: 

You must include the .cpp file which defines those extern variables and the function declared in your header in the compilation set. If the .cpp file containing the definitions is not compiled and linked against one which uses the declarations from your header file, you will get linker errors.

jMerliN
+2  A: 

Try this

Define those variables inside your header instead of just declaring them.

extern int x; is just a declaration(not a definition)

Simple example

a.cpp

 int a,b,c; //definition

 void doStuff(){ 

 }

b.cpp

extern int a,b,c; //extern keyword is mandatory
void doStuff();   //extern keyword is optional because functions by default have external linkage

int main()
{

   doStuff();
}
Prasoon Saurav
A: 

Are you sure you're linking in the object file that corresponds to the source file containing your methods and variables?

Mark B
Yes, I checked it.
A: 

Since you are using Visual-C++ (according to the tag), I'd just make sure that all your files are in the same project when compiling. Make sure you are building project and not just building a file.

I doubt this is the case, but you also might want to check that the source files are either compiled as C or as C++, or you might get into some trouble with the naming scheme.

Xzhsh