0

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?

Anon232
  • 3
  • 6
  • https://stackoverflow.com/questions/4448094/can-we-see-the-templates-instantiated-by-the-c-compiler – NathanOliver Jun 15 '23 at 12:47
  • 2
    You should move definitions into .cpp file so compiler won't be able to instantiate new code. – user7860670 Jun 15 '23 at 13:29
  • 2
    You can be pretty sure `main.cpp` instanciates the templates. Without adding `extern template struct Foo; extern template struct Foo;` to `FooHeader.hpp` the compiler just doesn't know that you're expecting the instanciation to be done in some other translation unit... – fabian Jun 15 '23 at 17:19

1 Answers1

0

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.

Anon232
  • 3
  • 6