为了简单起见,我将DLL_TUTORIAL.dll和头文件MathFuncsDll.h放在根文件夹C:\中。延迟加载DLL
然后,创建空的项目,设置
配置属性 - >连接器 - >输入 - >延迟加载的DLL的
到
C:\ DLL_TUTORIAL .dll;%(DelayLoadDLLs)
和
配置属性> VC++ Directories->包含目录
到
C:\; $(INCLUDEPATH)
编者命令:
/Zi/nologo/W3/WX-/O2/Oi/Oy-/GL/D“_MBCS”/ Gm-/EHsc/MT/GS /Gy/fp:precise/Zc:wchar_t/Zc: forScope /Fp"Release\clean_rough_draft.pch “/法 ”发布\“/ FO ”发布\“ /Fd"Release\vc100.pdb”/ GD/analyze-/errorReport:队列
该项目只包含带有main的文件。
的main.cpp
#include <Windows.h>
#include <iostream>
#include "MathFuncsDll.h"
using namespace MathFuncs;
using namespace std;
int main()
{
std::cout<< MyMathFuncs<int>::Add(5,10)<<endl;
system("Pause");
return 0;
}
的Dll已经在不同的解决方案成功编译。
MathFuncsDll.h
namespace MathFuncs
{
template <typename Type>
class MyMathFuncs
{
public:
static __declspec(dllexport) Type Add(Type a, Type b);
static __declspec(dllexport) Type Subtract(Type a, Type b);
static __declspec(dllexport) Type Multiply(Type a, Type b);
static __declspec(dllexport) Type Divide(Type a, Type b);
};
}
这些函数定义:
#include "MathFuncsDll.h"
#include <stdexcept>
using namespace std;
namespace MathFuncs
{
template <typename Type>
Type MyMathFuncs<Type>::Add(Type a,Type b)
{ return a+b; }
template <typename Type>
Type MyMathFuncs<Type>::Subtract(Type a,Type b)
{ return a-b; }
template <typename Type>
Type MyMathFuncs<Type>::Multiply(Type a,Type b)
{ return a*b; }
template <typename Type>
Type MyMathFuncs<Type>::Divide(Type a,Type b)
{
if(b == 0) throw new invalid_argument("Denominator cannot be zero!");
return a/b;
}
}
运行该程序失败:
1> main.obj:错误LNK2001:解析的外部符号“ public:static int __cdecl MathFuncs :: MyMathFuncs :: Add(int,int)“(?Add @?$ MyMathFuncs @ H @ MathFuncs @@ SAHHH @ Z) 1> C:\用户\托梅克\文档\ Visual Studio 2010的\项目\ clean_rough_draft \发布\ clean_rough_draft.exe:致命错误LNK1120:1周无法解析的外部
你能指出我的错误?
不支持导出模板方法。你必须把它们放在.h文件中。这留下了一个空的DLL。 –
详细说明,Template方法不是“真正的”方法 - 它们只是在编译时用于创建方法的模具。因此模板方法不能编译成目标代码。 – nakiya