MSVC DLL exporting class that inherits from template cause LNK2005 already defined error

本秂侑毒 提交于 2019-12-04 14:24:22

I have encountered the same problem recently. I managed to fix it finally so I will share my knowledge.

Source of the problem:

The template is instantiated multiple times. That is because you use implicit instantiation. Once when you declare class AA_API classA and once in the main when you declare Template< double > a; in main.

This means you will have more than one definitions for template.

  • 1, I am not sure why it is working in release mode (consider it to the lack of my deep knowledge with templates)
  • 2,3,4,when you get rid of any of the implicit template instantiation, you get rid of the multiple definitions
  • 5, maybe gcc does the instantiation differently, or there is a force multiply flag somewhere... I don't know
  • 6, This does not solve your problem, it just forces to accept the multiple instants.

Solution:

Explicit instantiation.

// aa/template.h
#pragma once
template<class T>
class Template {
public:
    Template() {}
};
template class Template<double>;  // Put this line after your template class.

Note: if the template class is in a different project, you need to export the instantiation.

I hope this will sort out your problem. It has fixed mine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!