本文介绍了使用外部dll时无法解析的外部符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试从外部dll使用函数时出现无法解析的外部符号错误!
这是导出的dll中的代码:

I got unresolved external symbol error when trying to use a function from external dll!Here is the code from exported dll:

//MathFunc.h
#pragma once

template <class T>
class MyMathFuncs
{
public:
    T Add(T a, T b);
};

extern "C" {
    MYAPI MyMathFuncs<int>* createInst(){
        return new MyMathFuncs<int>;
    }
}

//MathFunc.cpp
#include "MathFuncsDll.h"
#include <stdexcept>

using namespace std;

template <class T>
T MyMathFuncs<T>::Add(T a, T b)
{
    return a + b;
}

编译该项目后,我得到了.dll和.lib文件。之后,我创建了一个新项目,并将.dll文件添加到输出目录,并将.lib文件添加到链接器->输入->其他依赖项。这是新项目中的代码:

After compiling this project, I got .dll and .lib files. After that, I created a new project and added .dll file to output directory and .lib file to linker->Input->Additional dependencies. Here is code in the new project:

//main.cpp
#include <iostream>
#include "MathFuncsDll.h"

using namespace std;

int main(){
    MyMathFuncs<int> * pObj = createInst();
    cout << pObj->Add(1, 1) << endl;

    cin.get();
    return 0;
}

但是,当我编译时会导致错误:

However, when I compile it causes an error:

Error   1   error LNK2001: unresolved external symbol "public: int __thiscall       MyMathFuncs<int>::Add(int,int)" (?Add@?$MyMathFuncs@H@@QAEHHH@Z)    N:\Play around Code\DllApplication\DllApplication\main.obj

是因为我错误地导入了dll还是什么?我已经检查了新项目中所有项目的设置,其中包括其他包含项和其他依赖项(.lib)。

Is it because I have imported the dll wrongly or what? I have checked all the project's settings in the new project which included additional includes and additional dependencies(for .lib).

推荐答案

在类定义,您需要在生成 dll __ declspec(时指定 __ declspec(dllexport) dllimport),而我认为您正在使用 MYAPI

In the class definition, you need to specify __declspec(dllexport) while generating dll and __declspec(dllimport) while using it which I think you are doing with MYAPI.

更改类定义如下:

template <class T>
class MYAPI MyMathFuncs
{
public:
    T Add(T a, T b);
};

这篇关于使用外部dll时无法解析的外部符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 23:43