为了简单起见,我将 DLL_TUTORIAL.dll 与头文件 MathFuncsDll.h 放在根目录 C:\ 中。
然后,创建一个空项目,并设置
Configuration Properties -> Linker -> Input -> Delay Loaded Dll's
为
C:\DLL_TUTORIAL.dll;%(DelayLoadDLLs)
以及
Configuration Properties -> VC++ Directories -> Include 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" /Fa"Release\" /Fo"Release\" /Fd"Release\vc100.pdb" /Gd /analyze- /errorReport:queue 该项目仅包含 main.cpp 文件。
然后,创建一个空项目,并设置
Configuration Properties -> Linker -> Input -> Delay Loaded Dll's
为
C:\DLL_TUTORIAL.dll;%(DelayLoadDLLs)
以及
Configuration Properties -> VC++ Directories -> Include 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" /Fa"Release\" /Fo"Release\" /Fd"Release\vc100.pdb" /Gd /analyze- /errorReport:queue 该项目仅包含 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个无法解析的外部
您能指出我的错误吗?