window如何使用静态库

1. 静态库

1.1 静态库的生成

mylib.cpp中的内容

int add(int a, int b)
{
	return a + b;
}

1.2 静态库的使用

在代码里加上以下两句,然后配置库的路径
#pragma comment(lib, "myLib.lib")
extern int add(int a, int b);

配置库的路径

法二:不用

pragma comment(lib, "myLib.lib")

的方式加载静态库,在属性页中的链接器上设置
配置静态库

2. 动态库

2.1 动态库的生成

mydll.cpp

//使用纯C的方式导出
extern "C" __declspec(dllexport) int add(int a, int b) {
	return a + b;
}
//使用C++的方式导出  二者的函数名称不一样
__declspec(dllexport) int add2(int a, int b) {
	return a + b;
}

2.2 动态库的使用

#include <iostream>
#include <string>

#pragma comment(lib, "mydll.lib")
extern "C" __declspec(dllimport) int add(int a, int b);


int main()
{
	add(1, 2);
	return 0;
}

2.3 动态库的使用 不加载静态库

#include <iostream>
#include <string>
#include <Windows.h>


int main()
{
	HINSTANCE hDll = LoadLibrary(L"mydll.dll");
	if (hDll == NULL)
	{
		std::cout << "load dll failed!";
		return -1;
	}

	using functionPtr = int(*)(int, int);
	 
	functionPtr addFunction = (functionPtr)GetProcAddress(hDll, "add");
	if (addFunction == NULL) {
		std::cout << "connot find target function";
		return -1;
	}
	std::cout << addFunction(1, 2);
	return 0;
}

3. 常用的动态库的生成和使用方法

3.1动态库的生成

mydll.h

#pragma once

#ifndef DLL_IMPORT
#define API extern "C" __declspec(dllexport)
#else
#define API extern "C" __declspec(dllimport)
#endif

API int add(int a, int b);//函数的声明

mydll.cpp

#include "mydll.h"

//使用纯C的方式导出
API int add(int a, int b) {
	return a + b;
}

3.2动态库的使用

配置静态库路径
动态库的配置

#define DLL_IMPORT                //定义宏
#include <iostream>
#include <string>
#include <Windows.h>
#include "../dongtaiku/mydll.h"
#pragma comment(lib, "mydll.lib")//加载静态库,dll放在exe的运行路径


int main()
{
	std::cout << add(1, 2);
	
	return 0;
}

4. 导出类

类不能直接被导出

4.1 导出法1

mydll.h

#pragma once
#ifndef DLL_IMPORT
#define API __declspec(dllexport)
#else 
#define API __declspec(dllimport)
#endif

class API ExportClass {
public:
	int add(int a, int b);
};

mydll.cpp

#include "mydll.h"

int ExportClass::add(int a, int b)
{
	return a + b;
}

main.cpp

#include <iostream>
#include "../../ExprotClassDll/ExprotClassDll/mydll.h"

#pragma comment(lib, "ExprotClassDll.lib")

int main() {

	ExportClass instance;
	std::cout << instance.add(1, 2);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值