【问题标题】:Unresolved external symbol when invoking a template ctor调用模板ctor时未解析的外部符号
【发布时间】:2012-03-11 02:29:47
【问题描述】:

在创建模板类的实例时,我无法理解为什么会得到一个未解析的外部符号。

导致链接器错误的行是下面对 new 的调用:

Vbo<CustomVertex>*  m_pVbo;
...
m_pVbo = new Vbo<CustomVertex> ( 
  geometry.VertCount(), 
  geometry.Vertices(), 
  geometry.IndexCount(), 
  geometry.Indices() 
);

// nb: geometry.Vertices return type is CustomVertex**

Vbo类的定义如下:

template <typename T>
class Vbo : public glex
{
public:
  Vbo();
  Vbo( int nNumVerts, T** ppVertices, int nNumIndices, DWORD* pIndices );
  Vbo( const Vbo<T> & rhs );                        // copy
  Vbo<T> & operator=( const Vbo<T> & rhs );     // assignment
  ~Vbo();
...
}

以及Vbo构造函数的实现:

template <typename T>
Vbo<T>::Vbo( int nNumVerts, T** ppVertices, int nNumIndices, DWORD* pIndices ) :    
  m_bInitialized    ( false ),  
  m_nVboId          ( 0 ),
  m_nVboIdIndex     ( 0 ),  
  m_nNumVertices    ( nNumVerts ),
  m_nNumIndices     ( nNumIndices ),
  m_ppVertices      ( ppVertices ),
  m_pIndices        ( pIndices )
{
    glex::Load();
    Initialize();
}

最后,来自链接器的投诉:

1>Actor.obj : error LNK2019: unresolved external symbol "public: __thiscall Vbo::Vbo(int,class CustomVertex * *,int,unsigned long *)" (??0?$Vbo@VCustomVertex@@@ @QAE@HPAPAVCustomVertex@@HPAK@Z) 在函数 "private: bool __thiscall Actor::InitializeGeometry(class IGeometry &)" (?InitializeGeometry@Actor@@AAE_NAAVIGeometry@@@Z) 中引用 1>C:\cuprofen\Debug\Cuprofen.exe : 致命错误 LNK1120: 1 unresolved externals

有人能看出我的疏忽吗?

【问题讨论】:

    标签: c++ templates linker-errors


    【解决方案1】:

    Vbo 构造函数在哪里定义?我猜它在 .cpp 或 .cc 文件中,而不是在头文件中。模板函数定义需要在标头中(或者您可以使用更奇特的功能,如显式模板实例化)。这是因为模板函数仅在使用时才被理解为实际代码,并且我假设您的使用与您的定义不在同一个翻译单元中。

    【讨论】:

    • 是的,Vbo 构造函数是在 .cpp 文件中定义的。我会尝试将所有内容移到头文件中..
    • 谢谢,有趣的答案。我已将 Vbo 代码移到标题中,现在我的链接器错误消失了。你能定义“翻译单位”吗?
    • @freefallr:简单地说,它意味着一个源文件,以及其中包含的所有内容。
    猜你喜欢
    • 1970-01-01
    • 2011-08-12
    • 2014-06-13
    • 1970-01-01
    • 2010-12-23
    • 2016-06-19
    • 1970-01-01
    • 2011-02-09
    相关资源
    最近更新 更多