C:\Users\ologi\AppData\Local\Temp\ccq7ya3B.o:main.cpp:(.text+0x15): undefined reference to Vector<int>::Vector()
C:\Users\ologi\AppData\Local\Temp\ccq7ya3B.o:main.cpp:(.text+0x26): undefined reference to Vector<int>::append(int)
C:\Users\ologi\AppData\Local\Temp\ccq7ya3B.o:main.cpp:(.text+0x32): undefined reference to Vector<int>::print()
collect2.exe: error: ld returned 1 exit status
This is the error message that I get when compiling the files below:
main.cpp
#include "Vector.h"
int main(){
Vector<int> a = Vector<int>();
a.append(1);
a.print();
}
Vector.cpp
#include "Vector.h"
#include <iostream>
template <typename T>
T* Vector<T>::operator[](int index){
return get(index);
}
template <typename T>
T* Vector<T>::get(int index){
if (index < size)
return &(array[index]);
return nullptr;
}
template <typename T>
void Vector<T>::append(T obj) {
T* temp = new T[size+1];
copy(array, temp, size);
temp[size] = obj;
array = temp;
size++;
}
template <typename T>
void Vector<T>::copy(T* from, T* to, int from_size){
for (int i = 0; i < from_size; ++i){
to[i] = from[i];
}
}
template <typename T>
void Vector<T>::print(){
for (int i = 0; i < size; ++i){
std::cout << "[" << i << "]: " << array[i] << '\n';
}
}
template<typename T>
Vector<T>::Vector() {
size = 0;
}
Vector.h
#pragma once
template<typename T>
class Vector {
private:
T* array;
T* get(int);
public:
int size = 0;
Vector();
void append(T);
//void insert(T, int);
void remove(int);
void print();
void copy(T*, T*, int);
T* operator[](int);
};
I have tried with multiple commands and even CMake, still without success (the error message stays the same). I unfortunately don't even know where to start.
The commands I've tested:
g++ main.cpp
g++ -Wall -o main main.cpp Vector.cpp
g++ -c Vector.cpp -o Vector.o
g++ main.cpp Vector.o
I'm not sure it's a problem with the linker now. I've removed the template type from my class to check if that was the issue and fortunetly it's not.