In C and C++, we normally separate the declaration and the definition of
a function in two separated files: the header file contain the declaration of
the function (.h
or .hh
file) and the source code itself which
contain the definition of the function (.c
or .cpp
file). When
we would like to do the same with function containing template we get an error
of type undefined reference to
when the function is first used in code.
An example
For example let's suppose that the addition
function return the sum of
two numbers of same type.
First the header file (addition.hh
):
template<typename Type> Type addition(Type a, Type b);
Then the function source code (addition.cc
):
template<typename Type> Type addition(Type a, Type b)
{
return a + b;
}
Finally a small program using this function (main.cc
):
#include "addition.hh"
void main()
{
int a = 3;
int b = 2;
int c = 0;
c = addition(a, b)
}
While the code looks correct, the links creation will broke with the following error:
/tmp/ccEpROXj.o(.text+0x17c): In function `main':
: undefined reference to `addition(int, int)'
Why?
There are different reasons that this error appear. It is mainly because a template is not a function but a model used to generate the function. When it used by a program to generate the real function, the definition should be known and not only it's declaration.
How to solved it.
There is several solution to that problem.
The insertion of the definition in the header file.
The first one is to include the definition in the header file. For that, we only
need to fuse the two files (header and source code) in only one file or to
include the source code file with an include
preprocessing command at
the end of the header file. This solution is the easiest one, but not the
results is not so clean. Indeed, some compilers can increase dramatically the
size of the resulting binary.
Adding a template specialisation
FIXME: To be confirmed
We can also add the declaration of the specialisation that we want in the source code of the function.
For example, for the previous addition
function, we can specify the
declaration for types int
, float
and double
:
template<typename Type>
Type addition(Type a, Type b)
{
return a + b;
}
template int addition<int>(int, int);
template float addition<float>(float, float);
template double addition<double>(double, double);
By using the export
keyword.
FIXME