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

参考书目: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();
}

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

发布了34 篇原创文章 · 获赞 1 · 访问量 745

猜你喜欢

转载自blog.csdn.net/qq_41708281/article/details/104152266
今日推荐