I'm trying to code Matrices in C++, and weirdly enough, although everything was compiling fine; the moment i added a new constructor that takes a 2D array by ref, my build started always failing with this error:
1>Main.obj : error LNK2019: unresolved external symbol "public: __thiscall Matrix::Matrix<4,2>(double (&)[4][2])" (??$?0$03$01@Matrix@@QAE@AAY131N@Z) referenced in function _main
1>C:\Redacted\For\Privacy\Reasons\Matrix.exe : fatal error LNK1120: 1 unresolved externals
I tried compiling the code in a single file and it works fine : https://techiedelight.com/compiler/?IQe2
The only code i have right now is in 3 different files, Main.cpp
, Matrix.cpp
and Matrix.h
which are as follows:
// Main.cpp
#include "Matrix.h"
int main(char* args) {
double data[4][2] = {
{1,2},
{3,4},
{5,6},
{7,8}
};
Matrix* matrix = new Matrix(data);
std::cout << matrix->toString() << std::endl;
delete matrix;
}
// Matrix.cpp
#include "Matrix.h"
template<int r, int c>
Matrix::Matrix(double (&matrix)[r][c]) : ROW_DIM(r), COL_DIM(c), ELEMENTS_COUNT(r * c) {
data = new double[ROW_DIM * COL_DIM];
for (int x = 0; x < ROW_DIM; x++)
for (int y = 0; y < COL_DIM; y++)
data[x * COL_DIM + y] = matrix[x][y];
}
std::string Matrix::toString() {
std::string result = "";
for (int i = 0; i < ELEMENTS_COUNT; i++)
result.append(std::to_string(*(data + i)))
.append((i+1) % COL_DIM == 0 ? "\n" : " ");
return result;
}
#ifndef MATRIX_H
#define MATRIX_H
#include <iostream>
#include <string>
class Matrix
{
public:
template<int r, int c>
Matrix(double (&data)[r][c]);
std::string toString();
private:
const int ROW_DIM, COL_DIM, ELEMENTS_COUNT;
double* data;
};
#endif
I've been banging my head at this for 4h and I googled fatal error LNK1120
but all were unrelated to my specific case. Any ideas or help is greatly appreciated