1.静态库lib
生成解决方案会生成lib,最终lib文件嵌入在.exe文件中. 在其他工程中包含lib就能调用静态库中的函数
test
#include
#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;
}
2.动态库dll
在头文件中声明函数之前加__declspec(dllexport),eg:
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
其中__declspec(dllexport)用来申明导出add和sub函数,供其他工程调用dll时可以用add和sub两个函数,而当其他工程项目中调用add和sub时,再用DLLAPI申明时,表示的是__declspec(dllimport),即从动态库中导入add和sub函数。
在testdll工程属性-->C/C++-->预处理器-->预处理器定义中定义DLLAPI。
这样一来在其他工程中没有定义DLLAPI
隐式调用dll
在其他工程中隐式调用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;
}
显式调用dll
显示调用test.cpp
#include "stdafx.h"//头文件的添加有先后
#include
#include
#include //包含了HMODULE
#include
#include "../testdll/testdll.h"
//#include
//#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;
}