For maintainability reasons, I need to split the declaration and the definition of a template class. I want to know what is the correct way to compile the file if I'm using this design choice.
So, as a minimal reproducible example (using templated function just to be more compact) consider:
Header file foo.hpp where I declare a templated function myfun
//file foo.hpp
#ifndef foo_hpp
#define foo_hpp
template <typename T>
void myfun();
#endif /* foo_hpp */
Source file foo.cpp file where I define the function myfun
//file foo.cpp
#include "foo.hpp"
#include <iostream>
template <typename T>
void myfun(){
std::cout << "Call to myfunc \n";
}
template void myfun<int>();
Finally, the main.cpp file that uses myfun<int>
#include "foo.hpp"
int main(){
myfun<int>();
return 0;
}
I would compile and generate the executable test
from command line just by doing:
g++ -o test foo.cpp main.cpp
because in this way the linker is able to see the instantiation of myfun<int>
.
Is this the correct way to compile ?
EDIT:
Another possibility is to use a `.tpp file
//file foo.tpp
#include "foo.hpp"
#include <iostream>
template <typename T>
void myfun(){
std::cout << "Call to myfunc \n";
}
and put it into the .hpp file
//file foo.hpp
#ifndef foo_hpp
#define foo_hpp
template <typename T>
void myfun();
#include "foo.tpp"
#endif /* foo_hpp */
Finally, the main.cpp file that uses myfun<int>
#include "foo.hpp"
int main(){
myfun<int>();
return 0;
}
Now, I compile just by doing:
g++ -o test main.cpp
This works, but as I include the .tpp
(which includes the header) into the header, it seems I am including the header into itself, and it's pretty weird