【问题标题】:Preventing template instantiations in a static library防止静态库中的模板实例化
【发布时间】:2016-11-01 02:05:04
【问题描述】:

我正在尝试构建一个静态库,其中包含从各种 IDL 文件中获得的 DDS 主题的定义。我使用 OpenDDS 作为我的中间件。

当我创建一个包含 sequence<long> 的 IDL 文件,将其编译到我的静态库中,然后将静态库链接到我的应用程序时,我收到涉及多个符号定义的链接器错误:

Error   LNK2005 "public: void __cdecl TAO::unbounded_value_sequence<int>::length(unsigned int)" (?length@?$unbounded_value_sequence@H@TAO@@QEAAXI@Z) already defined in TAO.lib(TAO.dll)    

我相信这是因为我的静态库包含unbounded_value_sequence 的模板实例化,而我的应用程序也包含一个实例化。它似乎来自 OpenDDS 使用的 ACE TAO 内部。

我正在寻找一种方法来避免在我的静态库中完全实例化模板,以便当它们链接在一起时它可以只使用应用程序中的定义。我尝试添加以下内容:

extern template class TAO::unbounded_value_sequence<int>;

这产生了以下错误:

Error   C2961   'TAO::unbounded_value_sequence<CORBA::Long>': inconsistent explicit instantiations, a previous explicit instantiation did not specify '__declspec(dllimport)'

我试图找到那个实例,但它不在我的代码中。它可能在 ACE 内部。

如果我在一个项目中构建所有内容,则不会出现问题,但这不是一个理想的解决方案。

【问题讨论】:

    标签: c++ templates static-libraries ace opendds


    【解决方案1】:

    使用外部模板所要做的有点不同。事实上,声明 extern 模板会阻止它的实例化。但是您将需要一个实例化某处。这通常在一个 cpp 中,其中包含您要编译的模板的名称。

    unbounded_value_sequence.h:

    // template struct here
    
    extern template class TAO::unbounded_value_sequence<int>;
    extern template class TAO::unbounded_value_sequence<long>;
    // and every other instantiation you want to be in your static library
    

    unbounded_value_sequence.cpp:

    #include "unbounded_value_sequence.h"
    
    // Here you compile them one time.
    template class TAO::unbounded_value_sequence<int>;
    template class TAO::unbounded_value_sequence<long>;
    // and every other instantiation you want to be in your static library
    

    这将使您的模板在您的库中仅被实例化一次。编译器将生成一个包含模板实例化的unbounded_value_sequence 目标文件。它们只会存在于那里。

    不要忘记,如果您希望您的库的用户将您的模板类与他们的模板类一起使用,您仍然需要在标题中显示您的模板实现。

    【讨论】:

      猜你喜欢
      • 2013-02-11
      • 1970-01-01
      • 2011-04-11
      • 1970-01-01
      • 2023-03-09
      • 2011-10-27
      • 2017-10-03
      • 1970-01-01
      • 2015-08-14
      相关资源
      最近更新 更多