模板类 error LNK2019: 无法解析的外部符号

如果将类模板的声明和实现写在两个独立的文件中,在构建时会出现“error LNK2019: 无法解析的外部符号 ”的错误。

解决方法有:

  • 第一种方法,就是把类模板中成员函数的声明和定义都放在类的定义中(.h文件),不要分开就行。
  • 第二种方法,在主文件(main文件)中既包含类模板的声明文件(接口文件)(.h文件),同时也包含类模板的实现文件(.cpp文件)就行了。
  • 第三种方法,在类的定义中(.h文件)的最后包含类模板的实现文件(.cpp文件)。

 

原因在于模板类和模板函数在使用的时候才会被实例化。当模板被使用时,编译器需要函数所有的实现代码,来用合适的类型(模板参数)去构建正确的函数。但是如果将函数实现在单独的源文件中,这些文件是不可见的,因而会出错。

 

下面是摘自 StackOverflow的回答

Anyway, the reason your code is failing is that, when instantiating a template, the compiler creates a new class with the given template argument. For example:

template<typename T>
struct Foo
{
    T bar;
    void doSomething(T param) {/* do stuff using T */ }
};

// somewhere in a .cpp
Foo<int> f;

When reading this line, the compiler will create a new class (let's call it FooInt), which is equivalent to the following:

struct FooInt
{
    int bar;
    void doSomething(int param) {/* do stuff using int */ }
}

Consequently, the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case int). If these implementations were not in the header, they wouldn't be accessible, and therefore the compiler wouldn't be able to instantiate the template.

 

 

参考:

CSDN:模板类 error LNK2019: 无法解析的外部符号 

StackOverflow:Why can templates only be implemented in the header file?

转载于:https://www.cnblogs.com/VVingerfly/p/6124917.html

error LNK2019: 无法解析外部符号是指在链接时找不到符号的定义。这个错误通常发生在以下几种情况下: 1. 在C文件中定义了一个符号,但在C文件中声明时没有使用extern "C"。这意味着符号的链接方式不匹配,导致链接器无法找到符号的定义。 2. 使用了某个库中的内部函数,但没有正确指定编译选项。例如,在使用Intel Advanced Vector Extensions 2 instructions中的内部函数时,没有指定/ARCH:AVX2编译选项,导致内部函数被当作外部函数处理,无法找到。 3. 字符集不一致可能导致无法解析外部符号。在项目属性中,检查各个项目的字符集设置是否一致,如果不一致可能会导致链接器无法解析外部符号。 要解决这个错误,你可以尝试以下几个方法: 1. 在C文件中声明时使用extern "C",以确保链接方式匹配。这样可以将符号的链接方式设置为C链接,从而解决无法解析外部符号错误。 2. 确保在使用特定库的内部函数时,使用了正确的编译选项。根据库的要求,指定相应的编译选项,以确保内部函数正确地被链接。 3. 检查项目的字符集设置,并确保各个项目的字符集一致。如果字符集不一致,可以将它们统一设置为相同的字符集,以解决无法解析外部符号错误。 通过以上方法,你应该能够解决error LNK2019: 无法解析外部符号错误。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [error LNK2019: 无法解析外部符号 产生原因及修改方法](https://blog.csdn.net/weixin_42775777/article/details/113847405)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值