Friday 9 November 2018

c++ - Unresolved external symbol error while using vectors defined in a header file




I am new to C++. I had an unresolved external symbol error while using vectors and didn't know what was going wrong so I've replicated it here.



I am using MS Visual Studio 2011. The exact error is:




error LNK2001: unresolved external symbol "class std::vector > abc"
(?abc@@3V?$vector@VmyClass@@V?$allocator@VmyClass@@@std@@@std@@A)





I have my class declaration in myClass.h:



#ifndef __MYCLASS__
#define __MYCLASS__

class myClass{
public:
int var;
myClass(void);
myClass (int k);

};
#endif


and my class definition in myClass.cpp:



#include"myClass.h"

myClass::myClass(void){
var=0;

}
myClass::myClass (int k){
var=k;
}


header.h :



ifndef __HEADER__
#define __HEADER__


#include
#include
#include"myClass.h"
using namespace std;

extern std::vector abc;

#endif



main.cpp :



#include 
#include
#include "myClass.h"
#include "header.h"

using namespace std;


int main(){
abc.push_back(myClass(5));

return 1;
}


This is where I get the unresolved external symbol error. Now I tried putting all of these in a single file and it compiled alright.



THE FOLLOWING FILE IS NOT INCLUDED IN THE ABOVE PROJECT.




#include
#include
#include"myClass.h"
using namespace std;

class myClass{
public:
int var;
myClass(void){

var=0;
}
myClass (int k){
var=k;
}
};


int main(){
std::vector abc;

abc.push_back(myClass(5));

return 1;
}


The solution has been given at What is an undefined reference/unresolved external symbol error and how do I fix it?
but I can't figure out how to implement it.


Answer



You do not have a definition for this vector:




extern std::vector abc;


An extern declaration only tells the compiler that the object exists and it is defined somewhere. But you haven't defined it anywhere.



Add this at global namespace scope in one (and only one!) of your .cpp files:



std::vector abc;



Actually, considering that you are not using abc from different translation units (i.e. .cpp files) you do not need the extern declaration at all. Just place your vector in main.cpp, since that is the only place where you are using it.



Also, avoid using directives, especially at namespace scope (since it easily leads to nasty name clashes with entities from the Standard Library):



using namespace std; // THIS IS BAD, DON'T DO IT


Considering that you are qualifying the names of entities from the std namespace already, you don't really need the above.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...