Say I have a file foo.hpp
with a template
template<int a>
void foo()
{
// Complex function
}
which I use in my main.cpp
:
#include "foo.hpp"
int main()
{
// quickly compiled code
// ...
foo<3>();
// more quickly compiled code
}
Now each time I compile my project after changing main.cpp
, foo<3>()
needs to be compiled again, even though it doesn't change.
The vast majority of the compile time is spent compiling foo<3>()
in my case, so avoiding this is critical.
I would like to compile my project in two steps:
foo<3>()
. This takes long but I only do it once.main.cpp
. This is now fast because foo<3>()
is already compiled.How can I achieve this behavior? I tried doing explicit instantiation in a different file and compiling this first, but main.cpp
still takes the same time to compile.
Thanks for any help!
EDIT: Clarification of what I tried using explicit instantiation:
Create a new file precompiled.cpp
:
#include "foo.hpp"
template void foo<3>();
Then tried compiling this first with g++ -c precompiled.cpp
and afterwards, compile main.cpp
using g++ precompiled.o main.cpp
.
But this instantiates foo<3>()
again in step 2, which I want to avoid.
You're missing extern template void foo<3>();
in the header, after the definition of foo
.