本文以 Visual C++ 2003 為環境,以最簡潔的 Win32 主控台專案示範非 MFC DLL 的完整生命週期:建立、匯出函數、產生導入庫、以及兩種載入方式的實戰代碼。適合初學者快速掌握 DLL 核心機制。
選擇「Win32 主控台應用程式」→ 進階頁籤勾選「DLL」與「空白專案」。核心標頭檔 DLLTutorial.h 關鍵點:
#ifndef/_DEFINE 防重複包含extern "C" 防止 C++ 名稱修飾,確保 C/C++ 互通DLL_EXPORT 巨集切換 __declspec(dllexport) / dllimport#ifndef _DLL_TUTORIAL_H_
#define _DLL_TUTORIAL_H_
#include <iostream>
#if defined DLL_EXPORT
#define DECLDIR __declspec(dllexport)
#else
#define DECLDIR __declspec(dllimport)
#endif
extern "C" {
DECLDIR int Add(int a, int b);
DECLDIR void Function(void);
}
#endif
在 DLLTutorial.cpp 定義 DLL_EXPORT 後實作函數:
#include <iostream>
#include "DLL_Tutorial.h"
#define DLL_EXPORT
extern "C" {
DECLDIR int Add(int a, int b) { return a + b; }
DECLDIR void Function(void) { std::cout << "DLL Called!" << std::endl; }
}
建立 .def 檔同樣可匯出函數,非 Microsoft 專屬,攜帶性較佳:
LIBRARY dll_tutorial
DESCRIPTION "our simple DLL"
EXPORTS
Add @1
Function @2
編譯同時產生 .dll 與 .lib(導入庫),後者供隱式連結使用。
.h、.lib、.dll 複製至呼叫端專案目錄DLLTutorial.lib,或用 #pragma comment(lib, "DLLTutorial.lib")#include "DLLTutorial.h" 呼叫函數,無須額外代碼適用於外掛架構、選用性功能模組:
#include <iostream>
#include <windows.h>
typedef int (*AddFunc)(int, int);
typedef void (*FunctionFunc)();
int main() {
AddFunc _AddFunc = nullptr;
FunctionFunc _FunctionFunc = nullptr;
HINSTANCE hInst = LoadLibrary("DLL_Tutorial.dll");
if (!hInst) return 1;
_AddFunc = (AddFunc)GetProcAddress(hInst, "Add");
_FunctionFunc = (FunctionFunc)GetProcAddress(hInst, "Function");
if (!_AddFunc || !_FunctionFunc) { FreeLibrary(hInst); return 1; }
std::cout << _AddFunc(23, 43) << std::endl;
_FunctionFunc();
std::cin.get();
FreeLibrary(hInst);
return 0;
}
關鍵步驟:LoadLibrary 取得模組句柄 → GetProcAddress 取得函數位址 → 函數指標轉型呼叫 → FreeLibrary 釋放。
掌握 __declspec 與 .def 兩種匯出方式、隱式/顯式連結的適用場景,即具備 DLL 開發基礎。進階主題包含 DLL 生命週期管理 (DllMain)、執行緒區域儲存 (TLS)、跨模組記憶體管理、版本相容性等,留待後續探索。