静态链接库和动态链接库
Posted BGPY
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了静态链接库和动态链接库相关的知识,希望对你有一定的参考价值。
编译生成LIB
1>------ 已启动生成: 项目: test, 配置: Debug Win32 ------ 1> test.cpp 1> test.vcxproj -> D:\visual studio\test\Debug\test.lib ========== 生成: 成功 1 个,失败 0 个,最新 0 个,跳过 0 个 ==========
编译生成DLL:
#ifndef __ADD_H__ #define __ADD_H__ extern "C" int _declspec(dllexport) add(int x, int y); #endif
#include "add.h" int add(int a, int b) { return a + b; }
1> add.vcxproj -> D:\visual studio\add\Debug\add.dll
动态调用DLL(仅需要DLL,不需要头文件和LIB)
#include <iostream> #include <windows.h> using namespace std; typedef int(*FUN)(int, int);//定义指向和DLL中相同的函数原型指针 int main() { int x, y; HMODULE hDLL = LoadLibrary("D:\\visual studio\\add\\Debug\\add.dll");//加载dll if (hDLL != NULL) { FUN add = FUN(GetProcAddress(hDLL, "add"));//获取导入到应用程序中的函数指针,根据方法名取得 if (add != NULL) { cout << "Input 2 Numbers:"; cin >> x >> y; cout << add(x, y) <<endl; } else { cout << "Cannot Find Function" << endl; } FreeLibrary(hDLL); } else { cout << "Cannot Find dll" << endl; } return 1; }
Input 2 Numbers:3 4 7 请按任意键继续. . .
静态调用(同时需要头文件、LIB和DLL文件,缺一不可)
#ifndef __USEDll_H__ #define __USEDll_H__ extern "C" _declspec(dllimport) int add(int x, int y); #endif
#include "UseDll.h" #include <iostream> using namespace std; #pragma comment(lib,"D:\\visual studio\\UseDll\\Debug\\add.lib") int main() { int x, y; cout << "Input 2 Numbers:"; cin >> x >> y; cout << add(x, y) <<endl; }
Input 2 Numbers:10 10 20 请按任意键继续. . .
以上是关于静态链接库和动态链接库的主要内容,如果未能解决你的问题,请参考以下文章