I'm new to C++
I have been attempting to write a linked list below you can see I have linkedList header and implement and a main file I'm using MinGW-W64 as compiler
in my linkedList.h I have template struct Node
and a template class Vector2
// linkedList.h
template <class T>
struct Node
{
T value;
Node *next;
};
template <class T>
class Vector2
{
private:
Node<T> root;
public:
void add(T value);
~Vector2();
};
in my linkedList.cpp I implemented void Vector2<T>::add(T value);
and Vector2<T>::~Vector2();
// linkedList.cpp
#include <iostream>
#include "linkedList.h"
using namespace std;
template <class T>
void Vector2<T>::add(T value)
{
Node<T> *newNode = new Node<T>;
newNode->value = value;
if (root == nullptr)
{
newNode->value = nullptr;
root = newNode;
return;
}
newNode->next = root;
root = newNode;
}
template <class T>
Vector2<T>::~Vector2()
{
}
in main I created a Vector2 vec;
// main.cpp
#include <iostream>
#include "linkedList.h"
using namespace std;
int main()
{
Vector2<int> vec;
vec.add(12);
return 0;
}
when I compile my code I get this errors
$> make
g++ -g -Wall -o build\main main.cpp linkedList.cpp && echo Executing build\main && build\main.exe
\AppData\Local\Temp\ccb8gQgf.o: In function `main':
\Desktop\github\c\templates/main.cpp:9: undefined reference to `Vector2<int>::add(int)'
\Desktop\github\c\templates/main.cpp:10: undefined reference to `Vector2<int>::add(int)'
\Desktop\github\c\templates/main.cpp:11: undefined reference to `Vector2<int>::add(int)'
\Desktop\github\c\templates/main.cpp:8: undefined reference to `Vector2<int>::~Vector2()'
\Desktop\github\c\templates/main.cpp:8: undefined reference to `Vector2<int>::~Vector2()'
collect2.exe: error: ld returned 1 exit status
make: *** [makefile:13: main] Error 1
Template functions cannot be diveded as multiple files. You must inplement it in your header file.