Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile Templates located in different files in C++?

When I put all the source in one file, the program successfully builds. However when I split them into header files, I get a link error.

The main of my program: //C++_Class_Templates.cpp

#include <iostream>
#include <vector>
#include "Queue.h"

using namespace std;

//Usage for C++ class templates
void main()
{
     MyQueue<int> q;
     q.Add(1);
     q.Add(2);
}

The Queue.h looks like this

#pragma once
#include <vector>

template <typename T>
class MyQueue
{
     std::vector<T> data; 
   public:
     void Add(T const &);
     void Remove();
     void Print();

};

and the Queue.cpp looks like this:

#include "Queue.h"

template <typename T> void MyQueue<T> ::Add(T const &d)
{
     data.push_back(d);
}

When I try to build it, I get this error:

 1>main.obj : error LNK2019: unresolved external symbol "public: void __thiscall
 MyQueue<int>::Add(int const &)" (?Add@?$MyQueue@H@@QAEXABH@Z) referenced in function _main
like image 331
unj2 Avatar asked Dec 18 '25 17:12

unj2


2 Answers

The short answer is: "you don't."

The longer answer is: well, it's basically the same as the short answer. For more information, see the C++ FAQ Lite entry "Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?" Except for certain limited-use scenarios (like when you have a small set of known arguments with which you will use the template and you can explicitly instantiate it with those types), the definition of the template must be available when you try to use it.

like image 160
James McNellis Avatar answered Dec 21 '25 07:12

James McNellis


Separating declaration and definition for templates is not trivial.

The compiler must see the definition to be able to compile a specialization but it must also know the parameters to use. C++ was designed to be compiled one "compile unit" at a time and those two parts (the definition and the parameters) must be visible at the same time.

So either you put all a list of all specializations you will need in the implementation file of the template or you put the whole definition in the .h file. Both of those two solutions have however drawbacks.

See this answer to the same problem you are facing for a more complete explanation.

like image 30
6502 Avatar answered Dec 21 '25 05:12

6502



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!