Reputation:
I've been having some issues lately with my custom written general purpose vector code, which relies on templates for functionality. I am reluctant to include the implementation in the header file (as is common with templates), as this would add significantly to the compilation time. So I have instead manually instantiated the desired class in the .cpp file. However, this still results in an undefined reference error. I have reduced the code to the following snippet, which still generates an error:
matrixd.cpp
#include "matrixd.h"
namespace math
{
template class _vec2<float>;
template<class T> _vec2<T>::_vec2() {}
}
matrixd.h
#pragma once
namespace math
{
template <class T>
class _vec2
{
public:
T x, y;
_vec2<T>();
void reset();
};
typedef _vec2<float> vec2;
}
test.cpp
#include "matrixd.h"
int main()
{
math::_vec2<float> v;
}
Error message:
In function
main': source.cpp:(.text+0x10): undefined reference to
math::_vec2::_vec2()' collect2: error: ld returned 1 exit status
Any help would be appreciated! :)
Upvotes: 1
Views: 1403
Reputation: 137310
A explicit instantiation definition (template class _vec2<float>;
in your code) instantiates only the member functions that have been defined at the point of explicit instantiation. _vec2<T>::_vec2()
was defined after the explicit instantiation definition, and so is not explicitly instantiated.
The fix is to swap the two lines:
namespace math
{
template<class T> _vec2<T>::_vec2() {}
template class _vec2<float>;
}
Upvotes: 5