DLL实验 编程实现斐波那契数列前N项和、阶乘函数 VS
DLL实验
-
编程实现DLL,导出斐波那契数列前N项和、阶乘函数
-
.dll是动态链接库(Dynamic Link Library)的缩写。DLL是一个包含可由多个程序,同时使用的代码和数据的库。
-
可以更为容易地将更新应用于各个模块,而不会影响该程序的其他部分
创建DLL
-
创建DLL新项目
-
项目名字DLL1,正式创建
-
创建头文件Dll1.h,用于声明需要导出的函数
-
创建源文件Dll.cpp,用来存放源代码
-
同时为了让导出的函数名稳定,添加
.def
模块定义文件
此时项目文件入下所示
编写代码
于Dll1.cpp中编写代码,即导出斐波那契数列前N项和、阶乘函数
#include "Dll1.h"
#include "pch.h"
#include <stdio.h>
//菲波那切(Fibonacci)数列求和
int fbnq(int n)
{
if (n < 2) return n;
int a = 0;
int b = 1;
int c = 0;
int sum = 0;
for (int i = 2; i <= n; ++i) {
c = a + b;
a = b;
b = c;
sum += c;
}
return sum;
}
//阶乘函数
int fact(int n)
{
int sum = 1;
for (int i = 1; i <= n; i++)
sum = sum * i;
return sum;
}
头文件中声明两个函数
#pragma once
int fbnq(int n);
int fact(int n);
def
中也要声明
LIBRARY
EXPORTS
fbnq
fact
运行Dll会有如下弹窗,是正常现象
接下来我们进入项目路径,先找到.h
文件
接下来找到Debug文件夹,打开后寻找我们需要的.dll
和.lib
两个文件
调用
-
创建一个普普通通的C空项目,CDll
-
将之前提到的三个文件
.h、.dll、.lib
复制到项目路径下
-
导入
.h
头文件 -
创建测试代码
-
编写代码
#include <stdio.h> #include "Dll1.h" #pragma comment(lib, "Dll1.lib") int main() { int fb, fa; printf("The level of the Fibonacci sequence:"); scanf_s("%d", &fb); printf("The Fibonacci sequence of %d is %d", fb, fbnq(fb)); printf("\nThe desired level of factorial:"); scanf_s("%d", &fa); printf("%d!=%d", fa, fact(fa)); return 0; }
-
运行,运行结果正确
-
运行
.exe
也仅需要拖动到有.dll
和.lib
的目录即可