C++創建和使用動態鏈接庫

C++創建和使用動態鏈接庫

一個簡單的動態鏈接庫的生成和調用例子,太過簡單,大神請繞道。

一、創建動態鏈接庫

  1. 使用vs創建工程選擇動態鏈接庫。

  2. 在項目中創建源文件和頭文件,並在文件中添加以下代碼。

  3. 在頭文件中添加以下代碼

    // dlltest.h   頭文件,使用動態鏈接庫時需要包含頭文件
    
    #pragma once
    #ifdef __DLLEXPORT
    #define __DLL_EXP _declspec(dllexport)    // 導出函數 - 生成dll文件時使用
    #else
    #define __DLL_EXP _declspec(dllimport)    // 導入函數 -使用dll是使用
    #endif // __DLLEXPORT
    
    // 判斷是否是c++
    #if defined(__cplusplus)||defined(c_plusplus)
    extern "C"
    {
    #endif
     __DLL_EXP int add(int a, int b);
     __DLL_EXP int sub(int a, int b);
    
    #if defined(__cplusplus)||defined(c_plusplus)
    }
    #endif
  4. 在源文件文件中添加以下代碼

    // dlltest.cpp
    
    
    #include<stdio.h>
    #include"dlltest.h"
    #include"pch.h"
    
    
     int add(int a, int b)
    {
     return a + b;
    }
    
     int sub(int a, int b)
    {
     return a - b;
    }
  5. 在工程屬性,C/C++ => 預處理器 => 預處理定義 中添加預定義宏__DLLEXPORT.

  6. 在工程屬性,C/C++ => 預編譯頭 => 預處編譯頭 選擇不使用預編譯頭。

  7. 編譯生成dll文件和lib文件(如果沒有生成lib文件,需要在工程中添加一個Source.def文件,內容爲LIBRARY)。

二、使用動態鏈接庫

1. 使用c++調用動態鏈接庫

  1. 新建一個c++工程,包含dlltest.h頭文件,並引用生成的lib文件。

  2. 添加源文件testcpp.cpp,在源文件中輸入以下代碼:

    #include <iostream>
    #include"dlltest.h"
    
    int main()
    {
     printf("test cpp\n");
        std::cout << "Hello World!\n"; 
     printf("3+2 = %d\n", add(3, 2));
     printf("3-2 = %d\n", sub(3, 2));
    }
  3. 編譯,運行即可調用上面生成的動態鏈接庫。

2.使用c調用動態鏈接庫

  1. 新建一個c語言工程,包含dlltest.h頭文件,並引用生成的lib文件。

  2. 添加源文件testc.c,在源文件中輸入以下代碼:

    // testc.cpp : 此文件包含 "main" 函數。程序執行將在此處開始並結束。
    //
    #include <stdio.h>
    #include "dlltest.h"
    
    int main()
    {
     printf("test c\n");
     printf("3+2 = %d\n", add(3, 2));
     printf("3-2 = %d\n", sub(3, 2));
    }
    
    
  3. 編譯,運行即可調用上面生成的動態鏈接庫。

posted @ 2019-06-04 22:56 ay-a 閱讀(...) 評論(...) 編輯 收藏
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章