Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I avoid recompiling a specific template function each time I compile my project?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I would like to compile my project in two steps:

  1. Compile foo<3>(). This takes long but I only do it once.
  2. Compile 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.

>Solution :

You’re missing extern template void foo<3>(); in the header, after the definition of foo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading