【发布时间】:2012-08-22 00:34:37
【问题描述】:
为简单起见,我将 DLL_TUTORIAL.dll 和标头 MathFuncsDll.h 都放在了根文件夹 C:\ 中。
然后,创建空项目,设置
Configuration Properties->Linker->Input->Delay Loaded Dll's
到
C:\DLL_TUTORIAL.dll;%(DelayLoadDLLs)
和
配置属性->VC++ 目录->包含目录
到
C:\;$(IncludePath)
编译器命令:
/Zi /nologo /W3 /WX- /O2 /Oi /Oy- /GL /D "_MBCS" /Gm- /EHsc /MT /GS /Gy /fp:精确 /Zc:wchar_t /Zc:forScope /Fp"发布\clean_rough_draft.pch" /Fa"发布\" /Fo"发布\" /Fd"Release\vc100.pdb" /Gd /analyze- /errorReport:queue
此项目仅包含带有 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:\Users\Tomek\Documents\Visual Studio 2010\Projects\clean_rough_draft\Release\clean_rough_draft.exe : 致命错误 LNK1120: 1 unresolved externals
你能指出我的错误吗?
【问题讨论】:
-
不支持导出模板方法。您必须将它们放在 .h 文件中。这会留下一个空的 DLL。
-
详细地说,模板方法不是“真正的”方法——它们只是用于在编译时创建方法的模具。因此模板方法不会编译成目标代码。
标签: c++ visual-studio-2010 templates dll