So I've learnt that it's best to first declared function in header file, than define it in a seperate .cpp
file as function definition within headers aren't recommended. And I did so, with normal function and it worked. but when I try to do the same thing with template functions, it gave back error like
/usr/sbin/ld: /tmp/cc196bnS.o: in function `main':
test.cpp:(.text+0x11): undefined reference to `double d::numerical::test<double>(double)'
collect2: error: ld returned 1 exit status
Following will be a minimal working example where in header file I've define a normal function d::numerical::test2(double)
and a template function template<typename T> d::numerical::test(T)
. Then cout
their returning value individually in test.cpp
. Compiled with g++ integration.cpp test.cpp
, the one calling normal function test2
compiled and ran successfully, yet if I change it to test
it throws the error as shown above.
Notice I've also added a const
and a class in the header file, and those can also be accessed to ensure that the file actually get included properly.
I've read online (here) that it seems template functions' definition must also be in header file? But doesn't that goes against the rule that don't define function in header? What is the proper solution for these cases?
MWE
test.cpp
#include<bits/stdc++.h>
#include"./integration.hpp"
using namespace std;
int main() {
cout << d::numerical::test(1.) << std::endl;
return 0;
}
integration.hpp
#ifndef __FUNC_NUM_INTE__
#define __FUNC_NUM_INTE__
namespace d { namespace numerical {
const double EPS=1e-24;
double test2(double);
template<typename T> double test(T);
template<typename T>
class dp {
T odd, even;
};
}}
#endif
integration.cpp
#include"integration.hpp"
double d::numerical::test2(double x) {
return x;
}
template<typename T>
double d::numerical::test(T x) {
return x;
}