C++ 动态链接库DLL创建及使用

一、动态链接库DLL创建

使用VS2022 创建

1、创建新解决方案

 创建即可

2、创建动态链接库新项目

右键解决方案

语言选择C++,选择动态链接库

填入项目名称,勾选:将解决方案和项目放在同一目录中

点击创建

3、创建后,显示dllmain.cpp文件,新建.cpp和.h文件

 

点击右侧项目,右键——添加 ——新建项目(ctrl+shift+a)

修改名称,新建.cpp和.h文件

4、在.h和.cpp中填写代码

.h文件

#pragma once

#ifdef FIBONACCILIBRARY_EXPORTS
#define FIBONACCILIBRARY_API __declspec(dllexport)
#else
#define FIBONACCILIBRARY_API __declspec(dllimport)
#endif

/*
斐波那契递归关系描述了一个序列F
其中F(n) =  n = 0, a
                    n = 1, b
                    n > 1, F(n-2) + F(n-1)

对于一些初始积分值a和b。
如果序列初始化为F(0) = 1, F(1) = 1,
那么这个关系就产生了著名的斐波那契
序列:1,1,2,3,5,8,13,21,34,…
*/

/*
//初始化一个斐波那契关系序列
// F(0) = a, F(1) = b。
//该函数必须在其他函数之前调用。
*/
void InitFibonacci(const unsigned long long a, const unsigned long long b);

/*
生成序列中的下一个值。
成功返回true并更新当前值和索引;
溢出时为false,保持当前值和索引不变。
*/
bool NextFibonacci();

// 获取序列中的当前值
unsigned long long CurrentFibonacci();

// 获取当前值在序列中的位置
unsigned IndexFibonacci();

// 运行斐波那契函数
extern "C" FIBONACCILIBRARY_API void RunFibonacci(const unsigned long long a, const unsigned long long b);

.cpp文件

#include "pch.h" // use stdafx.h in Visual Studio 2017 and earlier
#include <utility>
#include <limits.h>
#include <iostream>
#include "FibonacciLibrary.h"

static unsigned long long _previous;
static unsigned long long _current;
static unsigned _index;              

void InitFibonacci(const unsigned long long a, const unsigned long long b)
{
    _index = 0;
    _current = a;
    _previous = b;
}

bool NextFibonacci()
{
    if ((ULLONG_MAX - _previous < _current) ||
        (UINT_MAX == _index))
    {
        return false;
    }

    if (_index > 0)
    {
        _previous += _current;
    }
    std::swap(_current, _previous);
    ++_index;
    return true;
}

unsigned long long CurrentFibonacci()
{
    return _current;
}

unsigned IndexFibonacci()
{
    return _index;
}

void RunFibonacci(const unsigned long long a, const unsigned long long b)
{
    InitFibonacci(a, b);

    do {
        std::cout << IndexFibonacci() << ": " << CurrentFibonacci() << std::endl;
    } while (NextFibonacci());

    std::cout << IndexFibonacci() + 1 << " Fibonacci sequence values fit in an unsigned 64-bit integer." << std::endl;
}

5、重要***:配置动态链接库

① 生成lib和dll文件到本项目目录中(生成到——> \x64\Debug 中)

将输出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值