使用mingw制作dll文件
-
准备math.c文件
//math.c
#include<stdio.h>
int add(int a,int b){
return a+b;
}
int sub(int a,int b){
return a-b;
}
int mul(int a,int b){
return a*b;
}
int div(int a,int b){
return a/b;
} -
制作dll
gcc math.c -shared -o math.dll -Wl,--out-implib,math.lib
生成 math.dll、math.lib
-
验证dll
-
编写加载dll文件的代码
#include<stdio.h>
#include <windows.h>
typedef int (*AddFunc)(int ,int);
typedef int (*SubFunc)(int ,int);
typedef int (*MulFunc)(int ,int);
typedef int (*DivFunc)(int ,int);
int main(void)
{
int a=10,b=2;
HMODULE hDll = LoadLibrary("math.dll");
if (hDll != NULL)
{
AddFunc add = (AddFunc)GetProcAddress(hDll, "add");
SubFunc sub = (SubFunc)GetProcAddress(hDll, "sub");
MulFunc mul = (MulFunc)GetProcAddress(hDll, "mul");
DivFunc div = (DivFunc)GetProcAddress(hDll, "div"); if (add != NULL)
printf("a+b=%d\n",add(a,b));
if (sub != NULL)
printf("a-b=%d\n",sub(a,b));
if (mul != NULL)
printf("a*b=%d\n",mul(a,b));
if (div != NULL)
printf("a/b=%d\n",div(a,b)); FreeLibrary(hDll);
}
} 编译
gcc loaddll_dynamic_show.c -o loaddll_dynamic_show.exe
运行
loaddll_dynamic_show.exe
-
结果
a+b=12
a-b=8
a*b=20
a/b=5
-