一 静态库
1 需要编译库时的头文件
2 需要.lib库文件
3 函数定义:extern "C" //声明为C编译、连接方式的外部函数
4 #pragma comment( lib, "..\\debug\\libTest.lib" ) //指定与静态库一起连接
二 普通DLL
1 extern "C" int __declspec(dllexport) //声明函数为DLL的导出函数
2 例子:
//lib.h
#ifndef LIB_H
#define LIB_H
extern "C" int __declspec(dllexport)add(int x, int y);
#endif
//lib.cpp
#include "lib.h"
int add(int x, int y)
{
return x + y;
}
//调用
#include <stdio.h>
#include <windows.h>
typedef int(*lpAddFun)(int, int); //宏定义函数指针类型
int main(int argc, char *argv[])
{
HINSTANCE hDll; //DLL句柄
lpAddFun addFun; //函数指针
hDll = LoadLibrary("..\\Debug\\dllTest.dll");
if (hDll != NULL)
{
addFun = (lpAddFun)GetProcAddress(hDll, "add");
if (addFun != NULL)
{
int result = addFun(2, 3);
printf("%d", result);
}
FreeLibrary(hDll);
}
return 0;
}
1 需要编译库时的头文件
2 需要.lib库文件
3 函数定义:extern "C" //声明为C编译、连接方式的外部函数
4 #pragma comment( lib, "..\\debug\\libTest.lib" ) //指定与静态库一起连接
二 普通DLL
1 extern "C" int __declspec(dllexport) //声明函数为DLL的导出函数
2 例子:
//lib.h
#ifndef LIB_H
#define LIB_H
extern "C" int __declspec(dllexport)add(int x, int y);
#endif
//lib.cpp
#include "lib.h"
int add(int x, int y)
{
return x + y;
}
//调用
#include <stdio.h>
#include <windows.h>
typedef int(*lpAddFun)(int, int); //宏定义函数指针类型
int main(int argc, char *argv[])
{
HINSTANCE hDll; //DLL句柄
lpAddFun addFun; //函数指针
hDll = LoadLibrary("..\\Debug\\dllTest.dll");
if (hDll != NULL)
{
addFun = (lpAddFun)GetProcAddress(hDll, "add");
if (addFun != NULL)
{
int result = addFun(2, 3);
printf("%d", result);
}
FreeLibrary(hDll);
}
return 0;
}