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 . . .
posted @ 2018-09-11 09:46  xbit  阅读(6511)  评论(0编辑  收藏  举报