静态链接
平台: WINDOWS2000/XP
工具: VC++ 6.0
创建步骤:
1. 新建项目: WIN32 STATIC LIBRARY;
2 选择PRE-COMPLILED HEADER;
3 编辑头文件和实现文件;
4 编译, 生成LIB文件;
参考代码:
//sum.h
#ifndef MYSUM
#define MYSUM
extern "C"
{
int Sum(int n);
}
#endif
//sum.cpp
#include "stdafx.h"
#include "sum.h"
int Sum(int n)
{
int iRet = 0;
for (int i=1;i<=n;i++)
{
iRet += i;
}
return iRet;
}
测试步骤:
1 新建一个WIN32 console 工程;
2 加入函数调用;
3 向工程中加入头文件和LIB文件;
4 编译,运行;
参考代码:
//main.cpp
#include "sum.h"
#include
int main()
{
printf("%d", Sum(n));
return 0;
}
WIN32动态链接
创建步骤:
1 新建项目: WIN32 DLL;
2 编辑头文件和实现文件;
3 编译, 生成LIB文件和DLL文件;
参考代码:
//sum.h
#ifdef __cplusplus
extern "C"
{
#endif
#ifdef SUM_EXPORTS
#define SUM_API __declspec(dllexport)
#else
#define SUM_API __declspec(dllimport)
#endif
SUM_API int Sum(int n);
#ifdef __cplusplus
}
#endif
//sum.cpp
#define SUM_EXPORTS
#include "sum.h"
int Sum(int n)
{
int iRet = 0;
for (int i = 1; i <= n ; i++)
{
iRet += i;
}
return iRet;
}
测试步骤:
1 新建一个WIN32 console 工程;
2 加入函数调用;
3 向工程中加入头文件和LIB文件;
4 将DLL文件放在可执行文件同一目录下
5 编译,运行;
静态装入参考代码:
//main.cpp
#include "sum.h"
#include "stdio.h"
int main(void)
{
printf("%d", Sum(100));
return 0;
}
动态装入参考代码:
//main.cpp
#include "sum.h"
#include "stdio.h"
#include
typedef int (*PFUNC)(int);
int main(void)
{
HINSTANCE hLib = ::LoadLibrary("dll");
if(hLib != NULL)
{
PFUNC pFunc = (PFUNC) ::GetProcAddress(hLib, "Sum");
if(pFunc != NULL)
{
printf("%d", pFunc(100));
}
else
printf("Function Not Found!");
}
else
{
printf("Library Not Found!");
}
return 0;
}
从DLL中导出类和成员函数
创建步骤:
1 新建项目: WIN32 DLL;
2 编辑头文件和实现文件;
3 编译, 生成LIB文件和DLL文件;
//cfoo.h
#ifdef CDLL_EXPORTS
#define CDLL_API __declspec(dllexport)
#else
#define CDLL_API __declspec(dllimport)
#endif
class CDLL_API CFoo {
public:
void Hello(void);
};
//cfoo.cpp
#include "stdafx.h"
#include "cfoo.h"
#include
void CFoo::Hello()
{
std::cout << "Hello DLL!" << std::endl;
}
测试步骤:
1 新建一个WIN32 console 工程;
2 加入函数调用;
3 向工程中加入头文件和LIB文件;
4 将DLL文件放在可执行文件同一目录下
5 编译,运行;
//main.cpp
#include "cfoo.h"
int main(void)
{
CFoo f;
f.Hello();
return 0;
}
使用MFC扩展DLL
假设要导出一个对话框,要修改的代码:
#ifndef _AFXEXT
#define IDD_EXT_NAME 129
#else
#include "resource.h"
#endif
class AFX_EXT_CLASS CNameDlg : public Cdialog
{…}