Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

std::vector<std::vector<float>> in header file throws error LNK1120

I want to include my own header file but vector< vector < float > > throws an error

matrix.cpp


#include <vector>

class Matrix
{
public:
    std::vector<std::vector<float>> data;
    Matrix(std::vector<std::vector<float>> d_data = { {} })
    {
        data = d_data;
    }

};

matrix.h

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


#ifndef MATRIX_H
#define MATRIX_H

#include <vector>


class Matrix {
public:
    std::vector<std::vector<float>> data;
    Matrix(std::vector<std::vector<float>> d_data = { {} });
};

#endif

matrixc++.cpp

#include <C:\Users\Matteo\source\repos\matrixc++\matrixc++\Matrix.h>
#include <vector>

int main()
{
    Matrix abc({{1,2},{2,1}});
    return 0;
}

Following error occurs :

matrixc++.obj : error LNK2019: unresolved external symbol "public: __cdecl Matrix::Matrix(class std::vector<class std::vector<float,class std::allocator >,class std::allocator<class std::vector<float,class std::allocator > > >)" (??0Matrix@@QEAA@V?$vector@V?$vector@MV?$allocator@M@std@@@std@@V?$allocator@V?$vector@MV?$allocator@M@std@@@std@@@2@@std@@@Z) referenced in function main

>Solution :

The problem is that you’ve more or less copy pasted the class definition to the source file matrix.cpp. That is, you have defined the class Matrix twice. Once in the header and second time in the source file.

To solve this just provide the implementation for the constructor Matrix::Matrix(std::vector<std::vector<float>>) inside the source file as shown below:

matrix.cpp

#include <C:\Users\Matteo\source\repos\matrixc++\matrixc++\Matrix.h>

//implement only the constructor
Matrix::Matrix(std::vector<std::vector<float>> d_data): data(d_data)
                                                        ^^^^^^^^^^^^ use constructor initializer list
{
    
}

matrix.h

#ifndef MATRIX_H
#define MATRIX_H

#include <vector>


class Matrix {
public:
    std::vector<std::vector<float>> data;
    Matrix(std::vector<std::vector<float>> d_data = { {} });
};

#endif

Working demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading