一.創建DLL
1.在VC中新建一個Win32空項目MathLib;
2.添加預編譯頭文件stdafx.h,定義導入導出控制符號:
代碼如下:
//stdafx.h
#pragma once
#define MATHLIB_EXPORT
3.添加包含要導出的全局變量,函數和類的頭文件MathLib.h:
代碼如下:
//MathLib.h
#pragma once
#ifdef MATHLIB_EXPORT
#define MATHLIBAPI __declspec(dllexport)
#else
#define MATHLIBAPI __declspec(dllimport)
#endif
//macro
#define PI 3.14149
//Global variable
extern MATHLIBAPI int GlobalVariable;
//Function
MATHLIBAPI int Add(int a,int b);
//Class
class MATHLIBAPI Math
{
public:
int Multiply(int a,int b);
};
4.添加所導出元素的實現文件MathLib.cpp
代碼如下:
//MathLib.cpp
#include "stdafx.h"
#include "MathLib.h"
int GlobalVariable = 100;
int Add(int a,int b)
{
return a+b;
}
int Math::Multiply(int a,int b)
{
return a*b;
}
二,測試所創建的DLL
測試代碼:
代碼如下:
#include "stdafx.h"
#include <iostream>
using namespace std;
#include "../MathLib/MathLib.h"
#pragma comment(lib,"../Debug/MathLib.lib")
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"Pi = "<<PI<<endl;
cout<<"GlobalVariable = "<<GlobalVariable<<endl;
int a = 20,b = 30;
cout<<"a="<<a<<", "<<"b="<<b<<endl;
cout<<"a+b = "<<Add(a,b)<<endl;
Math math;
cout<<"a*b = "<<math.Multiply(a,b)<<endl;
return 0;
}