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 . . .


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM