0

I am new to C++ and, for practice, have written my own vector class. The header file, Vector.h, is

#ifndef VECTOR_H_INCLUDED
#define VECTOR_H_INCLUDED

#include <cstddef>
#include <memory>

template <class T> class Vector {

    public:
        Vector();
       ~Vector();

    // code

};

#endif

The corresponding source file, Vector.cpp, is

#include "Vector.h"

template <class T> Vector<T>::Vector() 
{ 
    // code 
}

template <class T> Vector<T>::~Vector() 
{ 
    // code 
}

// code

The test file, VectorDemo.cpp, is

#include "Vector.h"

int main() 
{
    Vector<int> v;
    return 0;
}

In Bash I type

g++ -c Vector.cpp VectorDemo.cpp
g++ -o VectorDemo Vector.o VectorDemo.o

and get the following error

VectorDemo.o: In function `main':
VectorDemo.cpp:(.text+0x27): undefined reference to `Vector<int>::Vector()'
VectorDemo.cpp:(.text+0x38): undefined reference to `Vector<int>::~Vector()'
collect2: error: ld returned 1 exit status

How do I fix this issue and why is this happening?

tossimmar
  • 129
  • 5
  • I think you need a better system than `g++`-ing a bunch of stuff. Considered a `Makefile` or `CMakefile`? – tadman Nov 27 '20 at 02:13

1 Answers1

1

Template classes must be defined exclusively in the header. They cannot be compiled separately.

The reason for this is the compiler can only produce machine code for a specific instantiation of this template. The Vector.cpp file basically compiles to nothing, it's just a bunch of otherwise unused definitions.

Since these definitions don't amount to anything, they aren't instantiated within Vector.cpp, they're effectively ignored. When it comes time to compile VectorDemo.cpp they're missing, hence the linker errors.

tadman
  • 208,517
  • 23
  • 234
  • 262