您的位置:首页 > 其它

静态链接库和动态链接库编写

2016-05-20 12:41 381 查看
一 、静态链接库



1.创建lib.cpp和lib.h文件和普通的控制台的程序一样的写法即可

2.静态库的调用

a、把生成的.lib .h文件复制到调用文件中

b、包含这两个文件

#include”x.h”

#pragma comment(lib,”xx.lib”)

之后就可以使用了

lib.h

int add(int x,int y);


lib.cpp

#include "lib.h"
#include "StdAfx.h"
int add(int x,int y)
{
return x+y;
}


libtest.cpp

#include "lib.h"
#pragma comment(lib,"lib.lib")
int main(int argc, char* argv[])
{
printf("1+1=%d",add(1,1));
return 0;
}


二、动态链接库



1、同样是创建.h和.cpp文件

.h

extern "C" _declspec(dllexport) int add(int x,int y);


.cpp

#include "dll.h"

int add(int x,int y)
{
return x+y;
}

BOOL APIENTRY DllMain( HANDLE hModule,
DWORD  ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}


2、编译生成.lib和.dll文件,把他们复制到调用文件中

a、隐式调用

test.cpp

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#pragma comment(lib,"dll.lib")
extern "C" _declspec(dllimport) int add(int x,int y);
int main(int argc, char* argv[])
{
printf("1+1=%d",add(1,1));
return 0;
}


b、显示调用

test.cpp

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
///定义函数指针
typedef int (*lpFun)(int x,int y);
lpFun lpAdd;
HINSTANCE hMoudle=LoadLibrary("dll.dll");
if(hMoudle==NULL)
{
return 0;
}
lpAdd=(lpFun)GetProcAddress(hMoudle,"add");
printf("1+1=%d",lpAdd(1,1));
FreeLibrary(hMoudle);
return 0;
}


本文是学习笔记,有错误的地方请不吝赐教!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: