一個簡單的動態鏈接庫的生成和調用例子,太過簡單,大神請繞道。
一、創建動態鏈接庫
-
使用vs創建工程選擇動態鏈接庫。
-
在項目中創建源文件和頭文件,並在文件中添加以下代碼。
-
在頭文件中添加以下代碼
// 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
-
在源文件文件中添加以下代碼
// 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; }
-
在工程屬性,
C/C++ => 預處理器 => 預處理定義
中添加預定義宏__DLLEXPORT
. -
在工程屬性,
C/C++ => 預編譯頭 => 預處編譯頭
選擇不使用預編譯頭。 -
編譯生成dll文件和lib文件(如果沒有生成lib文件,需要在工程中添加一個Source.def文件,內容為LIBRARY)。
二、使用動態鏈接庫
1. 使用c++調用動態鏈接庫
-
新建一個c++工程,包含
dlltest.h
頭文件,並引用生成的lib文件。 -
添加源文件
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)); }
-
編譯,運行即可調用上面生成的動態鏈接庫。
2.使用c調用動態鏈接庫
-
新建一個c語言工程,包含
dlltest.h
頭文件,並引用生成的lib文件。 -
添加源文件
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)); }
-
編譯,運行即可調用上面生成的動態鏈接庫。