VS2017 DLL 生成与使用 最小例程

本文通过my_sum求和函数示例介绍如何创建和使用DLL。首先创建DLL项目并定义导出函数my_sum,然后编译生成Dll1.dll和Dll1.lib文件。接着在新的控制台应用程序项目中引入这些文件,并调用my_sum函数实现两数相加。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文以my_sum求和函数为例

生成DLL

创建DLL项目工程: file -> new project -> Installed -> Visual C++ -> Windows Desktop -> Dynamic-Link Library -> 工程名用默认的Dll1

编辑DLL工程:添加Dll1.h头文件,在里面输入如下代码

#ifdef DLL_EXPORTS
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif

DLL_API int my_sum(int a, int b);

在Dll1.cpp中添加如下代码

#include "stdafx.h"
#include "Dll1.h"

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

编译输出DLL:Build -> Build Solution,即可在工程目录的Debug文件夹下看到多个文件。其中Dll1.dll和Dll1.lib是后面要的文件。

使用DLL

新建项目:file -> new project -> Installed -> Visual C++ -> Windows Desktop -> Windows Console Application -> 输入项目名Dll1_test

复制dll文件:复制Dll1.dll、Dll1.lib和Dll1.h到项目文件夹的子目录Dll1_test下。

编辑测试代码:在Dll1_test.cpp中添加如下代码:

#include "stdafx.h"
#include "Dll1.h"
int main()
{
    int a = 1, b = 2;
    printf("%d + %d = %d\n", a, b, my_sum(a, b));
    return 0;
}

添加lib到资源文件

方法1: Solution Explorer -> Dll1_test -> Resource Files[右键] -> Add -> Existing Item -> 选中Dll1.lib -> Add

方法2:Solution Explorer -> Dll1_test[右键] -> Configuration Properties -> Linker -> Input -> Additional Dependencies -> Edit -> 添加Dll1.lib

编译运行Dll1_test

快捷键:CTRL+F5

或者 Build -> Build Solution,然后 Debug-> Start Without Debugging

如果成功,控制台第一行输出如下

1+2=3

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jiangjxiang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值