1

I understand that this is a common problem. I am asking again because I tried researching solutions but to no avail.

I am trying to implement a basic program using header files. There are three files main.cpp, method1.cpp and method1.h.

In method1.h, I have written template function declarations similar to the one below:

#include<vector>
template class<T>
std::vector<std::vector<T>> funFunc(std::vector<std::vector<T>> A, std::vector<std::vector<T>> B); 

In 'method1.cpp`, I have the following:

#include "method1.h"
#include<vector>
template class<T>
std::vector<std::vector<T>> funFunc(std::vector<std::vector<T>> A, std::vector<std::vector<T>> B)
{
     // Function Definition
}

Now, In main.cpp, I have something that calls these functions:

#include<iostream>
#include<vector>
#include "matrix.h"
int main()
{
    //Vector initializations
    funFunc(A, B)  //A and B have been initialized correctly as integer vectors.
}

When I try to compile these files using g++ main.cpp method1.cpp, I am getting the following error:

/tmp/ccd1KqmN.o: In function `main':
main.cpp:(.text+0x4bf): undefined reference to `std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > funcFunc<int>(std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >&, std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >&)
collect2: error: ld returned 1 exit status

I have compiled the code separately and there were no syntax errors.

After spending a lot of time trying to figure out what's wrong, I am unable to find out what's missing. I clearly understand that is a linker error and the g++ compiler is unable to find and link the object files correctly.

Can you please provide suggestions on how to resolve this?

Please comment if you require more information.

MVG
  • 314
  • 1
  • 3
  • 17
  • 1
    Template implementations belong in the template declaration ... – 2785528 Feb 27 '20 at 17:46
  • Thanks! Got the answer here too: https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – MVG Mar 02 '20 at 02:38

0 Answers0