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;
}