0

The following code in a single .cpp file works fine

#include <iostream>

template<typename T>
void print(int a) {
    std::cout << a << std::endl;
}

int main() {
    print<int>(5);
}

But if I separate the code into the files main.cpp, print.h and print.cpp respectively like this

#include "print.h"

int main() {
    print<int>(5);
}
template<typename T>
void print(int a);
#include <iostream>

template<typename T>
void print(int a) {
    std::cout << a << std::endl;
}

then gcc gives me the linker error "undefined reference to `void print<int>(int)'". Why does this happen? What is going wrong when declaring a template function? Is there some other way to do what I want?

  • TL;DR: A template is a _template_, not an actual function. This really doesn't mix with separate compilation because it needs an actual instantiation in order to produce anything concrete to link to. It's hard to give advice of how to work around it here besides the generic suggestions of using limited explicit instantiations, making it not a template, or accepting that it needs to be in the header. – chris Nov 18 '21 at 16:38

0 Answers0