Visual Studio dll export issue for class and function template instantiations

前端 未结 3 2035
心在旅途
心在旅途 2021-01-05 13:24

I am using VS2008 in win7 and g++ 4.7 in CentOS 18. The issue is only seen on Windows when I used dynamically shared library. When I convert it static library the program li

相关标签:
3条回答
  • 2021-01-05 14:02

    I worked out the problem. Under windows class template and function template are exported differently and there is a interesting reading on the net.

    VS compilers exports class template symbols if class template is instantiated on the translation unit (.cpp).

    However, in the case of function template, the keyword '__declspec(dllexport)' needs to be present explicitly for the symbols to be present on the dynamic library.

    e.g

    template EXPORT void HelpingRegistration<double>( double );
    //EXPORT is defined as __declspec(dllexport) 
    

    It's just another case where VS decide to things differently. There is interesting reading here: http://www.codesynthesis.com/~boris/blog/2010/01/18/dll-export-cxx-templates/

    0 讨论(0)
  • 2021-01-05 14:05

    I believe this is because compiler creates specialized code for template class when the template class is first used with a specific parameters. Since compiler uses only the included header files (.h) when compling a compilation unit (.cpp files) all the tmplate code must be available in .h files. You can export specialized template classes from a dll but not the template classes themselves.

    0 讨论(0)
  • 2021-01-05 14:25

    I believe you need to export the specializations. Have you tried this in your .cpp file:

    template class EXPORT TemplatedStaticLib<double>;
    template class EXPORT TemplatedStaticLib<std::string>;
    

    and pretty much the same in your header:

    template class EXPORT TemplateStaticLib<double>;
    template class EXPORT TemplateStaticLib<std::string>;
    

    I think that will work with your EXPORT macro (assuming the .cpp file see __declspec(dllexport) and the header sees __declspec(dllimport)). I admit I'm not an expert with Windows' __declspec.

    I admit that I drew my answer from this other answer on the intarwebs: http://social.msdn.microsoft.com/Forums/vstudio/en-US/4fd49664-e28e-4f23-b1eb-b669d35ad264/function-template-instantation-export-from-dll (scroll all the way to the bottom for Franjo555's final version.)

    0 讨论(0)
提交回复
热议问题