專案名稱:MyMathDLL
選擇DLL, 按下完成
MyMathDLL.cpp為專案的入口點, 內容為VC專案自動產生, 可以不用理他~
// MyMathDLL.cpp : 定義 DLL 應用程式的進入點。
分別新增MyMath.h 和 MyMath.cpp至專案, 如下圖所示
---------------------------------------------------------------------------------------
MyMath.h的內容如下:
#pragma once
class _declspec(dllexport) CMath
{
private:
int _a;
int _b;
int _mcd(int a, int b);
int _lcm(int a, int b);
public:
CMath(int a, int b);
int mcd();
int lcm();
};
---------------------------------------------------------------------------------------
MyMath.cpp的內容如下:
#include "stdafx.h"
#include "MyMath.h"
CMath::CMath(int a, int b)
{
_a = a;
_b = b;
}
int CMath::_mcd(int a, int b)
{
if(b==0)
return a;
return _mcd(b, a%b);
}
int CMath::mcd()
{
return _mcd(_a, _b);
}
int CMath::_lcm(int a, int b)
{
return a*b/_mcd(b, a%b);
}
int CMath::lcm()
{
return _lcm(_a, _b);
}
---------------------------------------------------------------------------------------
建立另一個Cosole專案呼叫上述的DLL
專案名稱: CallMyMathDLL
// CallMyMathDLL.cpp : 定義主控台應用程式的進入點。
//
#include "stdafx.h"
#include "MyMath.h"
#include <iostream>
using namespace std;
#pragma comment(lib, "MyMathDLL.lib")
int _tmain(int argc, _TCHAR* argv[])
{
CMath math(18, 24);
cout << math.mcd() << endl;
cout << math.lcm() << endl;
system("pause");
return 0;
}
新增一個WIN32 Console專案CallMyMathDLL至方案MyMathDLL之中
接著, 點選CallMyMathDLL並按下滑鼠右鍵, 選擇[屬性]
新增MyMath.h的路徑至其他Include目錄夾
新增MyMathDLL函式庫(LIB)的路徑
執行結果:
原始檔案: MyMathDLL.zip
下載後,請根據你解壓縮的位置修改CallMyMathDLL專案的Include和Library的路徑
Youtube 操作展示: 2013-04-19_如何從DLL輸出C++ Class