I get a linking error (LINK 2019) when I try to augment a class with template - c++

I'm trying to build a simple heap data structure for practice. When I build the version for double it works fine.
class heapt {
public:
heapt();
heapt(std::initializer_list<double> lst);
void print_heapt();
private:
int size;
int length;
double* elem; //points to root
};
Its constructors works perfectly and the heap is printed as it should. But when I try to generalize it with
template< typename Elem>
as:
template<typename Elem>
class heapt {
public:
heapt();
heapt(std::initializer_list<Elem> lst);
void print_heapt();
private:
int size;
int length;
Elem* elem; //points to root
};
for the class definition and as:
template<typename Elem>
heapt<Elem>::heapt(std::initializer_list<Elem> lst) :
size{ static_cast<int>(lst.size()) },
elem{new Elem[lst.size()]}
{
std::copy(lst.begin(), lst.end(), elem);//Now heaptify elem
build_heapt(elem, lst.size());
}
for one of the constructors used in the main function.
I get two linking errors:
LNK2019 unresolved external symbol "public: void __thiscall heapt::print_heapt(void)" (?print_heapt#?$heapt#H##QAEXXZ) referenced in function _main
LNK2019 unresolved external symbol "public: __thiscall heapt::heapt(class std::initializer_list)" (??0?$heapt#H##QAE#V?$initializer_list#H#std###Z) referenced in function _main
The main function is:
{
heapt<int> hh{ 27,12,3,13,2,4,14,5 };
std::cout << "Hello" << '\n';
hh.print_heapt();
}
EDIT: The heapt class is in the "heap.h" file and the definition for the constructor heapt<Elem>::heapt(std::initializer_list<Elem> lst) is in the "heap.cpp" class, which has #include"heap.h" as a header file. The int main function is in a file named "InSo.cpp", which also has #include"heap.h" as a header file.

In your templated class declaration you are using heapt(std::initializer_list<double> lst); but in your definition you are using std::initializer_list<Elem>. You should change the declaration to heapt(std::initializer_list<Elem> lst);
You are still missing definitions for print_heapt and build_heapt but otherwise it should compile.
EDIT: In light of you clarifying how your source files are set up, see WhozCraig's comment on your initial post. You can either include the definition of the templated class functions in a heap.hpp file, for example, and include it at the end of your heap.h, or just put them all together in one file, e.g.
// heap.h
#ifndef HEAP_H
#define HEAP_H
#include <initializer_list>
template<typename Elem>
class heapt {
public:
heapt();
heapt(std::initializer_list<Elem> lst);
void print_heapt();
private:
int size;
int length;
Elem* elem; //points to root
};
#include "heap.hpp"
#endif
//heap.hpp
#ifndef HEAP_HPP
#define HEAP_HPP
#include "heap.h"
#include <algorithm>
template<typename Elem>
heapt<Elem>::heapt(std::initializer_list<Elem> lst) :
size{ static_cast<int>(lst.size()) },
elem{ new Elem[lst.size()] }
{
std::copy(lst.begin(), lst.end(), elem);//Now heaptify elem
//build_heapt(elem, lst.size());
}
#endif

Related

C++ Unresolved External on Class in Project [duplicate]

This question already has answers here:
Why do I get "unresolved external symbol" errors when using templates? [duplicate]
(3 answers)
Closed 3 years ago.
So I'm new to C++ and Visual Studio and I'm trying to implement a hash table using templates. I have four files: main.cpp, HashNode.h, HashTable.h, and HashTable.cpp.
main calls the HashTable constructor with a paramenter (the definition is in HashNode.h, with the implementation in the cpp file), but this throws 2 unresolved external errors: one for the called constructor, and one for what I assume to be the default constructor.
However, main also calls the HashNode constructor with no problems. HashNode has its implementation and declaration all in the HashNode.h file, but moving HashTable's implementation to its .h file didn't clear the error. So I'm very confused lol.
I'm running Visual Studio 2019, fresh install, and using the default build button to build it. It does compile and run other things (like hello world), just not this.
I've also tried adding random garbage into HashTable.cpp to see if the compiler just didn't see that it existed, but that's not the case. It also throws a compilation error then.
HashTable.h:
#pragma once
#include "HashNode.h"
template <typename T>
class HashTable
{
public:
void AddItem(int key, T item);
T* GetItem(int key);
HashTable(int buckets);
~HashTable();
int print();
private:
HashNode<T>** elements;
int buckets;
};
HashTable.cpp:
#include "HashTable.h"
#include "HashNode.h"
#include <stdexcept>
template<typename T>
HashTable<T>::HashTable(int buckets)
{
elements = new HashNode<T> * [buckets];
for (int i = 0; i < buckets; i++)
{
elements[i] = nullptr;
}
HashTable::buckets = buckets;
}
... //other methods defined below
HashNode.h
#pragma once
template <typename V>
class HashNode
{
public:
HashNode(int key, const V value) : k(key), v(value), next(nullptr) {}
int getKey () const { return k; }
V getValue() const { return v; }
HashNode* getNext() const { return next; }
void setNext(HashNode* next) { HashNode::next = next; }
void appendToChain(HashNode* last)
{
HashNode* curr = this;
while (curr->getNext() != nullptr)
{
curr = curr->getNext();
}
curr.setNext(last);
}
private:
int k;
V v;
HashNode* next;
};
Main.cpp:
#include <iostream>
#include "HashTable.h"
#include "HashNode.h"
int main()
{
std::cout << "Hello World!\n";
HashNode<int> node(1,1); //works fine
std::cout << node.getValue() << std::endl; //prints fine
HashTable<int> table(5); //throws error on compilation
}
It's probably just something stupid or that I'm blind, but here's the errors:
Error LNK1120 2 unresolved externals HashTable D:\C++\HashTable\Debug\HashTable.exe 1
Error LNK2019 unresolved external symbol "public: __thiscall HashTable<int>::HashTable<int>(int)" (??0?$HashTable#H##QAE#H#Z) referenced in function _main HashTable D:\C++\HashTable\HashTable\Main.obj 1
Error LNK2019 unresolved external symbol "public: __thiscall HashTable<int>::~HashTable<int>(void)" (??1?$HashTable#H##QAE#XZ) referenced in function _main HashTable D:\C++\HashTable\HashTable\Main.obj 1
Also, please don't hesitate to give me pointers if my code's bad. I've never really programmed anything in C++ before so any help is welcome!
You need to move the template function definitions into the header file.
A longer answer can be found here.

C++: Templates not working from another class

When the following project is compiled, I get the following compiler error: (Visual Studio 2010)
1>usingclass.obj : error LNK2019: unresolved external symbol "public: static int __cdecl c1::arrSize(int * const)" (??$arrSize#H#c1##SAHQAH#Z) referenced in function "public: void __thiscall usingclass::a(void)" (?a#usingclass##QAEXXZ)
Code:
Headers:
c1.h
#pragma once
#include <array>
class c1
{
c1(void);
~c1(void);
public:
template<class T>
static int arrSize(T arr[]);
};
usingclass.h
#pragma once
#include "c1.h"
class usingclass
{
public:
usingclass(void);
~usingclass(void);
void a();
};
Source files:
c1.cpp
#include "c1.h"
c1::c1(void)
{
}
c1::~c1(void)
{
}
template <class T>
int c1::arrSize(T arr[])
{
return (sizeof(arr)/sizeof(arr[0]));
}
usingclass.cpp
#include "usingclass.h"
usingclass::usingclass(void)
{
}
usingclass::~usingclass(void)
{
}
void usingclass::a()
{
int a[2] = {1,2};
int b = c1::arrSize<int>(a);
}
How do I fix that?
Don't do this! The declaration is misleading.
template <class T>
int c1::arrSize(T arr[])
{
return (sizeof(arr)/sizeof(arr[0]));
}
is equivalent to
template <class T>
int c1::arrSize(T *arr)
{
return (sizeof(arr)/sizeof(arr[0]));
}
which will not give you want you want. The proper way to do it is like this:
class c1
{
c1(void);
~c1(void);
public:
template<class T,int N>
static int arrSize(T (&arr)[N]) { return N; }
};
arrSize takes a reference to an array as a parameter. The type of the array and the size of the array are template parameters and can be deduced by the compiler. The inline member function then just returns the size determined by the compiler.
You need to move
template <class T>
int c1::arrSize(T arr[])
{
return (sizeof(arr)/sizeof(arr[0]));
}
inside c1.h.
Template implementations must be visible to all translation units using that template (unless it's specialized, and in your case it's not).
This solves the compiler error but the underlying issue is solved with Vaughn Cato's answer. I missed that. You'll still need the definition in the header.
I think you have to define your template in c1.h itself. Because when you are including c1.h in your usingclass.h, and try to use template it does not find the expansion for template.
Or If you want to go with implementation of template in c1.cpp, then you have to include c1.cpp as well in usingclass.h.

Constructor linker error using template

I just started using template.
I want to create a linked list class which stores the address of Type (could be an object). Here is the layout of my project:
linkedlist.h
node.h
node.cpp
linkedlist.cpp
main.cpp
Node.h
template <class Type> struct Node
{
public:
Node<Type>();
Node<Type>(Type* x = 0, Node* pNext = 0);
Type* data;
Node* next;
};
Node.cpp
#include "node.h"
template<class Type> Node<Type>::Node()
{
next = 0;
data = 0;
}
template<class Type> Node<Type>::Node(Type* item, Node* ptrNext)
{
next = ptrNext;
data = item;
}
linkedlist.h
#include "node.h"
template <class Type> class LinkedList
{
private:
Node<Type>* root;
public:
LinkedList<Type>();
~LinkedList<Type>();
void insert(Type*);
void remove(Type*);
};
linkedlist.cpp
#include "linkedlist.h"
template <class Type> LinkedList<Type>::LinkedList()
{
root = 0;
}
template <class Type> LinkedList<Type>::~LinkedList()
{
Node* p;
while(p = root)
{
root = p->next;
delete p;
}
}
// many more....
In main.cpp, I have the following:
int main()
{
int *ptrA, *ptrB;
int a = 100, b = 10;
ptrA = &a;
ptrB = &b;
LinkedList<int>myList;
myList.insert(ptrA);
return 0;
}
and compiler threw linker errors:
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall LinkedList<int>::~LinkedList<int>(void)" (??1?$LinkedList#H##QAE#XZ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: void __thiscall LinkedList<int>::insert(int *)" (?insert#?$LinkedList#H##QAEXPAH#Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall LinkedList<int>::LinkedList<int>(void)" (??0?$LinkedList#H##QAE#XZ) referenced in function _main
Attempted Solution:
I called LinkedListmyList() instead. This can resolve the linker error, but I will not be able to call any member function.
myList.insert(ptrA) will say "Error: Expression must have a class type" if I put ().
So clearly this is not working.
What's the problem? I think the whole implementation has problems....
Thanks for your time.
Move the stuff from linkedlist.cpp .. to linkedlist.h
As it's declaring a 'template for making code' the machine code doesn't actually exist until you give the compiler the type you want to use.
For example, as long as all the template code is visible to the compiler, as soon as you go: LinkedList<int>myList the compiler creates the solid real class that makes a linkedlist of ints. In your case, the compiler can't see the template code, so isn't able to generate the machine code.
in c++11 you can say 'extern template': http://en.wikipedia.org/wiki/C%2B%2B11#Extern_template
in the header file, then implement the 'int' version in your linkeList.cpp file .. and it'll be available in main.cpp when it tries to use it.
This gives the advantage of the compiler not having to generate the machine code in every .cpp file where the template is used and makes compiling faster.
It can be done in c++98 too .. but it's a bit more tricky and not 100% portable as I understand it .. easier to just generate the code everywhere. Here's a good blurb on it for gnu gcc: http://gcc.gnu.org/onlinedocs/gcc/Template-Instantiation.html

Define sorting method ( that use std::sort for sorting) of a templated class in dll and calling it from another project

Sorry for my bad English. I have 2 projects. Project 1 is a MFC dll that contains class CMyContainer, class CEmployee. Project 2 is my main project. In project 2, I created an instance of CMyContainer of type CEmployee. Now I want to sort the container but I got an error
"error LNK2019: unresolved external symbol "bool __cdecl MyComparer(class CEmployee *,class CEmployee *)" (?MyComparer##YA_NPAVCEmployee##0#Z) referenced in function "public: void __thiscall CMyContainer<class CEmployee>::sortContainer(void)" (?sortContainer#?$CMyContainer#VCEmployee####QAEXXZ)"
How can I fix this problem?
// file MyContainer.h in project 1
#include <vector>
template <class T>
class _declspec(dllexport) CMyContainer
{
public:
CMyContainer(void);
~CMyContainer(void);
...
void sortContainer();
private:
std::vector<T*> items;
typename std::vector<T*>::iterator it;
};
template <class T> void CMyContainer<T>::sortContainer()
{
typedef bool (*comparer_t)(T*,T*);
comparer_t cmp = &MyComparer;
std::sort(items.begin(), items.end(), cmp);
}
//File Employee.h in project 1
#include "MyContainer.h"
class _declspec(dllexport) CEmployee
{
public:
CEmployee(void);
~CEmployee(void);
void setEmployeeCode(CString);
CString getEmployeeCode();
friend bool MyComparer(CEmployee*, CEmployee*);
private:
CString m_szEmployeeCode;
}
//File Employee.cpp in project 1
void CEmployee::setEmployeeCode(CString val){
m_szEmployeeCode= val;
}
CString CEmployee::getEmployeeCode(){
return m_szEmployeeCode;
}
bool MyComparer(CEmployee*pEmp1, CEmployee*pEmp2)
{
return (pEmp1->getEmployeeCode().Compare(pEmp2->getEmployeeCode())<0);
}
//File main.cpp in project 2
#include <..\Models\MyContainer.h>
#include <..\Models\Employee.h>
...
CMyContainer<CEmployee> *pListEmployee;
... // insert into pListEmployee
// sort pListEmployee
pListEmployee.sortContainer();//-> This command cause error
Try to export MyComparer from the .dll with _declspec(dllexport)

C++ - LNK2019 error unresolved external symbol [template class's constructor and destructor] referenced in function _main

[[UPDATE]] -> If I #include "Queue.cpp" in my program.cpp, it works just fine. This shouldn't be necessary, right?
Hey all -- I'm using Visual Studio 2010 and having trouble linking a quick-and-dirty Queue implementation. I started with an empty Win32 Console Application, and all files are present in the project. For verbosity, here's the complete code to duplicate my error. I realize some of the code may, in fact, be wrong. I haven't had a chance to test it yet because I haven't yet been able to link it.
Queue.hpp
#ifndef ERROR_CODE
#define ERROR_CODE
enum Error_Code
{
Success,
Underflow,
Overflow
};
#endif // ERROR_CODE
#ifndef QUEUE
#define QUEUE
template<class T>
struct Queue_Node
{
T data;
Queue_Node *next;
Queue_Node()
{
next = NULL;
}
Queue_Node(T pData)
{
data = pData;
next = NULL;
}
Queue_Node(T pData, Queue_Node *pNext)
{
data = pData;
next = pNext;
}
};
template<class T>
class Queue
{
public:
Queue();
Error_Code Serve();
Error_Code Append(T item);
T Front();
~Queue();
private:
void Rescursive_Destroy(Queue_Node<T> *entry);
Queue_Node<T> *front, *rear;
};
#endif // QUEUE
Queue.cpp
#include "Queue.hpp"
template <class T>
Queue<T>::Queue()
{
this->front = this->rear = NULL;
}
template<class T>
Error_Code Queue<T>::Serve()
{
if(front == NULL)
return Underflow;
Queue_Node *temp = this->front;
this->front = this->front->next;
delete temp;
}
template<class T>
Error_Code Queue<T>::Append(T item)
{
Queue_Node *temp = new Queue_Node(item);
if(!temp)
return Overflow;
if(this->rear != NULL)
this->rear->next = temp;
this->rear = temp;
return Success;
}
template<class T>
T Queue<T>::Front()
{
if(this->front == NULL)
return Underflow;
return this->front->data;
}
template<class T>
Queue<T>::~Queue()
{
this->Rescursive_Destroy(this->front);
}
template<class T>
void Queue<T>::Rescursive_Destroy(Queue_Node<T> *entry)
{
if(entry != NULL)
{
this->Recursive_Destroy(entry->next);
delete entry;
}
}
program.cpp
#include "Queue.hpp"
int main()
{
Queue<int> steve;
return 0;
}
And the errors...
Error 1 error LNK2019: unresolved external symbol "public: __thiscall Queue<int>::~Queue<int>(void)" (??1?$Queue#H##QAE#XZ) referenced in function _main C:\[omitted]\Project2_2\Project2_2\program.obj Project2_2
Error 2 error LNK2019: unresolved external symbol "public: __thiscall Queue<int>::Queue<int>(void)" (??0?$Queue#H##QAE#XZ) referenced in function _main C:\[omitted]\Project2_2\Project2_2\program.obj Project2_2
Why don't you follow the "Inclusion Model"? I'd recommend you follow that model.
The compiler needs to have access to the entire template definition (not just the signature) in order to generate code for each instantiation of the template, so you need to move the definitions of the functions to your header.
Note: In general most C++ compilers do not easily support the separate compilation model for templates.
Furthermore you need to read this.
An example for solving the error lnk2019:
It has to write #include "EXAMPLE.cpp" at the end of .h file
//header file codes
#pragma once
#ifndef EXAMPLE_H
#define EXAMPLE_H
template <class T>
class EXAMPLE
{
//class members
void Fnuction1();
};
//write this
#include "EXAMPLE.cpp"
#endif
//----------------------------------------------
In the .cpp file do as following
//precompile header
#include "stdafx.h"
#pragma once
#ifndef _EXAMPLE_CPP_
#define _EXAMPLE_CPP_
template <class T>
void EXAMPLE<T>::Fnuction1()
{
//codes
}
#endif
//-----------------------------------------------
All template code need to be accessible during compilation. Move the Queue.cpp implementation details into the header so that they are available.
The linker errors are because it sees the header files for Queue.hpp, but doesn't see the definitions of the functions. This is because it is a template class, and for C++, the definitions of templates must be in the header file (there are a few other options, but that is the easiest solution). Move the defintions of the functions from Queue.cpp to Queue.hpp and it should compile.
If you have:
template <typename T>
void foo();
And you do:
foo<int>();
The compiler needs to generate (instantiate) that function. But it can't do that unless the function definition is visible at the point of instantiation.
This means template definitions needs to be included, in some way, in the header. (You can include the .cpp at the end of the header, or just provide the definitions inline.)