0

I'm trying my hand at some template stuff, and the first thing I wanted to do was to separate templated classes into .hpp and .cpp files. All examples I've found say to just include

template class Foo<int>;

at the bottom of the .cpp-file, but I can't get this to work. Here is a minimal example:

foo.hpp

#pragma once

template<typename T>
class Foo
{
public:
    Foo(T t);

private:
    T _t;
};

foo.cpp

#include "foo.h"

template<typename T>
Foo<T>::Foo(T t) : _t(t) {}

template class Foo<int>; // explicit instantiation

main.cpp

// main.cpp
#include "foo.hpp"

int main()
{
    Foo<int> a(5);
}

This does not compile, but gives an error undefined reference to 'Foo<int>::Foo(int)'

$ g++ main.cpp -o main
C:\msys64\tmp\cc4EtmTs.o:main.cpp:(.text+0x1a): undefined reference to `Foo<int>::Foo(int)'
collect2.exe: error: ld returned 1 exit status

I'm using MSYS2, with gcc 8.3.0 (Rev2, Built by MSYS2 project). Any idea what I'm doing wrong?

Filip S.
  • 1,514
  • 3
  • 19
  • 40

0 Answers0