I'm trying to compile a file that includes a hpp file. The two functions declared in utility.hpp and implemented in utility.cpp use a template class to accept any type of input such that it's possible to call println(12) as well as println("test"). However, I'm struggling to compile it. If I compile it without using the hpp file it works fine, i.e. if I include directly the cpp file it works but if I include the hpp file as shown below it fails.
Command line (Ubuntu 18.04):
g++ -o test test.cpp utility.cpp
Error obtained:
/tmp/ccl5rHBI.o: In function `main':
test.cpp:(.text+0x17): undefined reference to `void println<char const*>(char const*)'
collect2: error: ld returned 1 exit status
Files:
// test.cpp
#include "utility.hpp"
int main(int argc, char const *argv[])
{
println("test");
return 0;
}
// utility.hpp
#ifndef UTILITY_HPP_
#define UTILITY_HPP_
template<class T>
void print(T toPrint);
template<class T>
void println(T toPrint);
#endif
// utility.cpp
#include <iostream>
#include "utility.hpp"
template<class T>
void print(T toPrint){
std::cout << toPrint;
}
template<class T>
void println(T toPrint){
std::cout << toPrint << std::endl;
}
So my question is: How to fix it and compile those files such that the functions keep the property to accept any type of input.
Thanks in advance.