您的位置:首页 > 其它

【静态库&动态库】用最简单的例子说明静态库动态库的操作

2016-04-30 11:09 417 查看
<span style="font-size:18px;background-color: rgb(255, 0, 0);">编译环境VS2013</span>

//注意:在调用库文件的时候,需要将你的库文件放在你的工程目录下

//静态库
//lib.c  将lib.c属性改成静态库文件,然后生成
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>

void msg()
{
MessageBoxA(0, "#pragma comment(lib 0801_静态库与动态库.lib)", "静态库调用", 0);
}

int add(int a, int b)
{
return a + b;
}

//main.c  调用静态库

#include<stdio.h>
#include<stdlib.h>

//调用静态库
#pragma comment(lib, "0801_静态库与动态库.lib")
//头文件只是说明,lib自己就存在借口
void main()
{
printf("%d\n", add(99,78)) ;//
msg();
}
动态库
//dll.c  将dll.c的属性改成动态库
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>

_declspec(dllexport) void msg()
{
MessageBoxA(0, "#pragma comment(lib 0801_静态库与动态库.lib)", "静态库调用", 0);
}

_declspec(dllexport) int add(int a, int b)
{
return a + b;
}

//动态库调用
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>

typedef void(*pmsg)(); <span style="white-space:pre">			</span>//简化函数指针
typedef int(*padd)(int a, int b);

void main()
{
HMODULE mydll = LoadLibraryA("动态库.dll");//加载动态库
if (mydll == NULL)
{
printf("动态库调用失败\n");
}
else
{
padd padd1; //定义一个函数指针
padd1 = (padd)GetProcAddress(mydll, "add");//从动态库中获取msg()的地址
if (padd1 != NULL)
{
printf("%d\n", padd1(10, 20));//调用函数
}
pmsg pmsg1; //定义一个函数指针
pmsg1 = (pmsg)GetProcAddress(mydll, "msg");//从动态库中获取msg()的地址
if (pmsg1 != NULL)
{
pmsg1();//调用函数
}
}
FreeLibrary(mydll);
//反注射 可以劫持该函数
system("pause");
}
//动态库静态库的区别:
//动态库 谁都可以用, 不用更新exe,更新dll即可实现功能更新,节约
//计算机资源需要使用的时候调用,否则释放。动态库可以实现劫持。
//静态库 可以实现库文件私有,每次更新。需要重新编译exe。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: