静态库&动态库创建
1.静态库lib
生成解决方案会生成lib,最终lib文件嵌入在.exe文件中. 在其他工程中包含lib就能调用静态库中的函数
test
include<stdio.h>
include
include"../testlib/textlib.h"
pragma comment(lib, "testlib.lib")//会将所有的静态库文件嵌入到exe文件中,包含的lib越多,exe文件越大
//动态库dll不用嵌入exe,所以exe不会很大
int main()
{
printf("请输入两个整数\n");
int a, b;
scanf("%d%d", &a, &b);//调用静态库
printf("a+b=%d\n",add(a, b));
printf("a-b=%d\n", sub(a, b));
system("pause");
return 0;
}
testdll.h
#ifndef __DLL #define __DLL
ifdef DLLAPI
#define DLLAPI __declspec(dllexport)
else
#define DLLAPI __declspec(dllimport)
endif // DLLAPI
extern "C" DLLAPI int add(int a, int b); //使用extern "C"表面使用C语言的方式导出函数,
//否则用C++的方式导出,会导致函数名发生改变
extern "C" DLLAPI int sub(int a, int b);endif // !__DLL
另一个工程下的test.cpp
#include
#include #include #include "stdafx.h" #include "../testdll/testdll.h" #pragma comment (lib,"testdll.lib")//隐式调用动态库 int main()
{
int a, b;
printf("请输入两个整数:");
scanf_s("%d%d", &a, &b);printf("a+b=%d", add(a, b)); printf("a-b=%d", sub(a, b)); system("pause"); return 0;
}
显示调用test.cpp
#include "stdafx.h"//头文件的添加有先后 #include
#include #include //包含了HMODULE #include include "../testdll/testdll.h"
//#include<opencv2\opencv.hpp>
//#pragma comment (lib,"testdll.lib")//隐式调用动态库typedef int(PADD)(int a, int b);
typedef int(PSUB)(int a, int b);int main()
{
//加载dll文件
HMODULE hdll = LoadLibrary(L"../x64/Debug/testdll.dll");
if (hdll == NULL)
{
printf("cannot load testdll.dll");
return 0;
}int a, b; printf("请输入两个整数:"); scanf_s("%d%d", &a, &b); PADD padd = (PADD)GetProcAddress(hdll, "add"); PSUB psub = (PSUB)GetProcAddress(hdll, "sub"); printf("a+b=%d", padd(a, b)); printf("a-b=%d", psub(a, b)); FreeLibrary(hdll); system("pause"); return 0;
}
Don't be one of the leeches