本文包括以下内容:
1. 如何编译生成dll和lib文件
2. 如何在外部程序调用dll(动态链接)并访问其函数
3. 如何在外部程序调用lib(静态链接)并访问其函数
一、如何编译生成dll和lib文件
1. 新建Win32控制台程序,勾选dll
2. 新建mydll.h文件,写入代码:
#ifndef _CLASS_H_
#define _CLASS_H_
//declaration
extern "C" __declspec(dllexport) int add(int a ,int b);
#endif
3. mydll.cpp文件,写入代码:
#include "stdafx.h"
#include "ClassDLL.h"
//implement
__declspec(dllexport) int add(int a ,int b)
{
return a+b;
}
二、外部调用dll
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
using namespace std;
/*dynamic call*/
typedef int(*lpAddFun)(int, int);
int _tmain(int argc, _TCHAR* argv[])
{
/* dynamic call */
HINSTANCE hDll;
lpAddFun addFun;
hDll = LoadLibrary(L"E:/ClassDLL.dll");
if (hDll != NULL)
{
addFun = (lpAddFun)GetProcAddress(hDll, "add");
if (addFun != NULL)
{
int result = addFun(2, 3);
cout<<result;
}
FreeLibrary(hDll);
}
return 0;
}
三、外部调用lib
#include "stdafx.h"
#include "DoorFSM.h"
#include <Windows.h>
#include <iostream>
using namespace std;
/*static call*/
#pragma comment(lib,"D:/ClassDLL.lib")
extern "C" __declspec(dllimport) int add(int x,int y);
int _tmain(int argc, _TCHAR* argv[])
{
/* static call */
int result = add(2,3);
cout<<result<<endl;
return 0;
}