C++ Shared Library with Templates: Undefined symbols error

后端 未结 4 1382
广开言路
广开言路 2020-12-04 11:08

I\'m trying to link to a shared library with a template class, but it is giving me \"undefined symbols\" errors. I\'ve condensed the problem to about 20 lines of code.

4条回答
  •  长情又很酷
    2020-12-04 11:40

    In addition to the other answers, you can explicitly instantiate template classes. This is only useful if you know beforehand what types the template parameters may assume. You instantiate the template with all these types in the library.

    For your example to compile, just add the following to the end of shared.cpp:

    // Instantiate myclass for the supported template type parameters
    template class myclass;
    template class myclass;
    

    This instantiates the template with Type=int and places the instantiated code in the shared library. Add as many explicit instantiations as you need, for all the types you need.

    Again, if you want to be able to instantiate the template with any arbitrary Type parameter, then you must add the definitions to the header file, so that the compiler knows the source code of the template when instantiating it in other compilation units.

提交回复
热议问题