VS2017 创建并测试 C++ dll

 

生成DLL

  1. 创建工程: Create new project -> 选择Visual C++ -> Windows Desktop -> Dynamic-Link Library (DLL) -> 输入工程名dll_exam
  2. 查看EXPORTS宏:右键工程 -> Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions -> 里面应该也有一个DLLEXAM_EXPORTS,这个后面会用到。
  3. 添加dll_exam.h文件,输入代码如下:
    #pragma once
    
    #ifdef DLLEXAM_EXPORTS
    #define DLLEXAM_API __declspec(dllexport)
    #else
    #define DLLEXAM_API __declspec(dllimport)
    #endif
    
    DLLEXAM_API int dll_sum(int a, int b);
    
    class DLLEXAM_API dll_class {
    public:
        dll_class();
        ~dll_class();
        int x;
        int y;
        int sum(void);
    };
  4. 在dll_exam.cpp文件输入如下代码:
    #include "dll_exam.h"
    
    int dll_sum(int a, int b)
    {
        return a + b;
    }
    
    dll_class::dll_class()
    {
        x = 1;
        y = 2;
    }
    
    dll_class::~dll_class()
    {
    }
    
    int dll_class::sum(void)
    {
        return x+y;
    }
  5. 编译,将编译结果dll_exam.dll、dll_exam.lib和dll_exam.h添加到调用的工程目录。

 调用DLL

  1. 创建工程: Create new project -> 选择Visual C++ -> Windows Desktop -> Windows Console Application -> 输入工程名test_dll_exam
  2. 右键工程 -> Properties -> Linker -> Input -> Additional Dependencies -> 输入dll_exam.lib
    或者 右键Resource Files -> Add -> Existing Item -> 添加dll_exam.lib
  3. 在test_dll_exam.cpp中输入如下代码:
    #include "stdafx.h"
    #include "dll_exam.h"
    #include <iostream>
    int main()
    {
        std::cout<< "dll_sum(3,5) = " << dll_sum(3,5) << std::endl;
        dll_class dll_obj;
        std::cout<< "dll_obj.sum() = " << dll_obj.sum() << std::endl;
        return 0;
    }
  4. 编译运行Ctrl+F5,结果如下:
    dll_sum(3,5) = 8
    dll_obj.sum() = 3
    Press any key to continue . . .

转载于:https://www.cnblogs.com/xbit/p/9625743.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值