学习笔记:自定义动态库的建立和使用

参考书目:C/C++规范设计简明教程,P288

编程环境:VS2017

第一步: 建立动态链接库项目”MyFirstDLL“

第二步:添加头文件-first.h

#pragma once
#include "pch.h"

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
using namespace std;
__declspec(dllexport) void display();
__declspec(dllexport) int getMax(int a, int b);	//获得两数字之间的较大值

第三步:在cpp文件中添加函数体

定义了两个函数display, getMax。

// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "pch.h"
#include "first.h"
BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}


__declspec(dllexport) void display()
{
	printf("正在调用动态链接库!\n");
}

__declspec(dllexport) int getMax(int a, int b)	//获得两数字之间的较大值
{
	return a > b ? a : b;
}

第四步:编译,生成.dll、.lib文件。

第五步:建立测试文件”“

第六步:首先编译一下,产生debug文件夹

将MyFirstDLL.lib、first.h拷贝到Test_MyFirstDll\Test_MyFirstDll文件夹下

将MyFirstDLL.dll拷贝到Test_MyFirstDll\Debug文件夹下。

在工程中,引入first.h文件。

第七步:修改first.h文件,把dllimport,修改为dllexport

修改后,first.h如下:

#pragma once
//#include "pch.h"

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
using namespace std;
__declspec(dllexport) void display();
__declspec(dllexport) int getMax(int a, int b);	//获得两数字之间的较大值

第八步:编写主文件

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "first.h"
using namespace std;

#pragma comment(lib, "MyFirstDLL.lib")
int main()
{
	cout << "Hello World!\n";

	display();
	cout << "5,2之间较大的值为:" << getMax(5, 2) << endl;

	getchar();
}

第九步:编译,运行。结果如下:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值