Explicit instantiation across multiple libraries

54 Views Asked by At

If I have some header with a template implementation:

#ifndef FOOHEADER_HPP
#define FOOHEADER_HPP
template <typename T>
struct Foo
{
void FooFun(){}
};
#endif

And two .cpp-files which provides explicit instantiations of this declaration:

FloatFoo.cpp:

#include "FooHeader.hpp"
template struct Foo<float>;

IntFoo.cpp:

#include "FooHeader.hpp"
template struct Foo<int>;

I can compile the .cpp-files to libraries IntFoo.so and FloatFoo.so.

The implementations will be used in an executable based on main.cpp:

#include "FooHeader.hpp"
int main()
{
    Foo<float> foo;
    Foo<int> iFoo;
    iFoo.FooFun();
    foo.FooFun();
}

When compiling the executable:

clang++ main.cpp -L./ -lIntFoo -lFloatFoo

How do I know if the compiler actually used the instantiations in IntFoo,FloatFoo, or if it instantiated new code implicitly from the initialization in main.cpp?

1

There are 1 best solutions below

0
Anon232 On

extern template struct Foo<> in main.cpp solves this issue, as suggested by @fabian. With the following main.cpp:

#include "FooHeader.hpp"
extern template struct Foo<float>;
extern template struct Foo<int>;


int main()
{
    Foo<float> foo;
    Foo<int> iFoo;
    iFoo.FooFun();
    foo.FooFun();
}

The compiler will throw error if libraries IntFoo and FloatFoo are not linked.