When trying to compile the code below, I get the following error:
$ g++ -std=c++11 main.cpp src/matrix.cpp
/tmp/ccsVOKfQ.o: In function `main':
main.cpp:(.text+0x1b): undefined reference to `matrix<int>::matrix(unsigned int, int)'
main.cpp:(.text+0x2c): undefined reference to `matrix<int>::operator[](int)'
collect2: error: ld returned 1 exit status
As far as I know all the code is included correctly, it even worked fine in Visual Studio, but for some reason refuses to compile in GCC on Linux, giving the above error.
My Code:
src/matrix.hpp:
#ifndef __matrix_hpp
#define __matrix_hpp
#include <vector>
#include "../lib/typedefs.hpp"
// abstraction layer on top of 2D vector
template <typename t>
class matrix {
private:
std::vector<std::vector<t>> _mat;
uint _size;
public:
matrix(uint, t);
std::vector<t> get_row(int);
std::vector<t> get_column(int);
std::vector<t>& operator[](int);
matrix transpose();
};
#endif
src/matrix.cpp:
#include "matrix.hpp"
template <typename t>
matrix<t>::matrix(uint size, t default_val) {
_size = size;
_mat = std::vector<std::vector<t>>(_size, std::vector<t>(_size, default_val));
}
template <typename t>
std::vector<t> matrix<t>::get_row(int row_number) {
return _mat[row_number];
}
template <typename t>
std::vector<t> matrix<t>::get_column(int col_number) {
std::vector<t> column;
for (int r = 0; r < _size; r++)
column.push_back(_mat[r][col_number]);
return column;
}
// provided as alternative notation to get_row
template <typename t>
std::vector<t>& matrix<t>::operator[](int i) {
return get_row(i);
}
main.cpp:
#include <iostream>
#include <cstdio>
#include "src/matrix.hpp"
int main() {
matrix<int> m(9, 0); // test constructor
m[1][2] = 100; // test operator overload
return 0;
}
How can I resolve this issue and make the code compile?