1

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

当我创建一个包含sequence<long>.

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 内部。

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

4

1 回答 1

1

使用 extern 模板所要做的有点不同。事实上,声明 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包含您的模板实例化的目标文件。它们只会存在于那里。

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

于 2016-11-01T18:06:10.157 回答