为什么我得到“未解析的外部符号”使用模板时出现错误? [英] Why do I get "unresolved external symbol" errors when using templates?

查看:162
本文介绍了为什么我得到“未解析的外部符号”使用模板时出现错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用模板编写类的C ++代码并在源(CPP)文件和头文件(H)之间拆分代码时,我得到了大量的未解决的外部符号错误,当谈到链接最终可执行,尽管目标文件被正确构建并包含在链接中。

When I write C++ code for a class using templates and split the code between a source (CPP) file and a header (H) file, I get a whole lot of "unresolved external symbol" errors when it comes to linking the final executible, despite the object file being correctly built and included in the linking. What's happening here, and how can I fix it?

推荐答案

模板化的类和函数在使用之前不会实例化,通常在一个单独的.cpp文件(例如程序源)。当使用模板时,编译器需要该函数的完整代码才能构建具有适当类型的正确函数。但是,在这种情况下,该函数的代码在模板的源文件中详细描述,因此不可用。

Templated classes and functions are not instantiated until they are used, typically in a separate .cpp file (e.g. the program source). When the template is used, the compiler needs the full code for that function to be able to build the correct function with the appropriate type. However, in this case the code for that function is detailed in the template's source file and hence unavailable.

作为所有这些的结果,编译器只是假定它在其他地方定义,只插入对模板函数的调用。当涉及到编译模板的源文件时,程序源中使用的特定模板类型不在那里使用,因此它仍然不会生成函数所需的代码。

As a result of all this the compiler just assumes that it's defined elsewhere and only inserts the call to the templated function. When it comes to compile the template's source file, the specific template type that is being used in the program source isn't used there so it still won't generate the code required for the function. This results in the unresolved external symbol.

可用的解决方案是:



  1. 模板的头文件中包含
    的成员函数的完整定义,而没有模板的
    a源文件,

  2. 定义所有成员函数在
    模板的源文件为
    inline或

  3. 定义成员
    函数在模板的源
    与export关键字。
    不幸的是,很多编译器不支持
    (更新:这已从C ++ 11的标准中删除。)

  1. include the full definition of the member function in the template's header file and not have a source file for the template,
  2. define all the member functions in the template's source file as "inline", or
  3. define the member functions in the template's source with the "export" keyword. Unfortunately this isn't supported by a lot of compilers. (Update: this has been removed from the standard as of C++11.)

当你试图在程序源代码中创建类型化函数时,1和2基本上都可以通过给编译器访问模板函数的完整代码来解决这个问题。

Both 1 and 2 basically address the problem by giving the compiler access to the full code for the templated function when it is attempting to build the typed function in the program source.

这篇关于为什么我得到“未解析的外部符号”使用模板时出现错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆