首先介绍静态链接库*.lib的链接
Step1.创建一个lib文件
//lib.h #ifndef _LIB_H #define _LIB_H int add(int a = 0,int b = 0); #endif
//lib.cpp #include "lib.h" int add(int a,int b) { return a+b; }
Step2.在main函数中调用lib #pragma comment(lib,"..\\debug\\libTest.lib")
#include "..\\libTest\\lib.h" #include <iostream> using namespace std; #pragma comment(lib,"..\\debug\\libTest.lib");//与指定的*.lib库链接 int main(int argc,char **argv) { cout <<add(3,5)<<endl;//直接使用lib库中的函数 }
动态链接库Dll的链接
Way1.动态链接方式
Step1.在*.h中声明那个函数是DLL导出函数,供应用程序使用,否则是DLL内部函数,只能DLL内部调用
extern"C" int __declspec(dllexport) add(int a = 0,int b =0);//声明库文件中的add函数为导出函数,注意这里的“extern ‘C’ ”是为了向上兼容,如果源文件(lib.cpp)是.c文件就不加
//DllTest.h #ifndef _DLLTEST_H #define _DLLTEST_H extern"C" int __declspec(dllexport) add(int a = 0,int b =0); #endif
//DllTest.cpp #include "DllTest.h" int add(int a,int b) { return a+b; }
Step2.在main中使用Dll
主要有三步:LoadLibary("*.dll")加载DLL模块;
GetProcAddress();
FreeLibrary();
#include <Windows.h> #include <iostream> using namespace std; typedef int (*pfn)(int,int);//定义一个函数指针,同库中导出函数同参,同返回值 int main(int argc,char **argv) { HINSTANCE hDll; pfn pfnadd; hDll = ::LoadLibrary("..\\Debug\\DllTest.dll");//动态加载DLL模块,并将模块句柄赋给hDll if (hDll != NULL) { pfnadd = (pfn)GetProcAddress(hDll,"add");//得到所加载的DLL模块中的add函数地址 if (pfnadd !=NULL) { cout<< pfnadd(2,3)<<endl; } } FreeLibrary(hDll);//使用完后释放资源 return 0; }
Way2.DLL的静态调用方式 ------在编译时加载DLL,程序结束后卸载DLL
Step1.将*.lib与*.dll拷贝至项目目录下
Step2.main程序中
#pragma comment(lib,"DllTest.lib");//lib文件是其对应的dll文件中函数重定位信息
extern"C" int __declspec(dllimport) add(int,int);
#include <iostream> using namespace std; #pragma comment(lib,"DllTest.lib"); extern"C" int __declspec(dllimport) add(int,int); int main(int argc, char **argv) { cout<<add(3,4)<<endl;//直接使用库函数 return 0; }
【热爱工作,热爱生活】