首先创建C++ DLL项目并使用__declspec(dllexport)导出函数,然后通过隐式链接或显式加载在其他程序中调用DLL功能,需注意函数命名、运行库依赖及文件部署。

在Windows平台上,使用C++编写动态链接库(DLL)是一种常见的模块化编程方式。DLL允许你将功能封装成独立的文件,在多个程序之间共享,同时便于更新和维护。下面介绍如何创建和使用一个简单的C++ DLL。
创建一个C++动态链接库(DLL)
我们以Visual Studio为例说明创建过程,但原理适用于任何支持Windows C++编译器的环境。
1. 创建DLL项目
打开Visual Studio,选择“创建新项目” → “动态链接库(DLL)”,选择C++模板,命名项目(例如 MyMathLib)。
2. 编写导出函数
在头文件(如 MathFunctions.h)中声明要导出的函数,并使用 __declspec(dllexport) 标记:
// MathFunctions.h
#pragma once
<h1>ifdef __cplusplus</h1><p>extern "C" {</p><h1>endif</h1><p><strong>declspec(dllexport) int Add(int a, int b);
</strong>declspec(dllexport) int Multiply(int a, int b);</p><h1>ifdef __cplusplus</h1><p>}</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/6e7abc4abb9f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">C++免费学习笔记(深入)</a>”;</p><h1>endif</h1>
在源文件中实现这些函数:
// MathFunctions.cpp
#include "MathFunctions.h"
<p>int Add(int a, int b) {
return a + b;
}</p><p>int Multiply(int a, int b) {
return a * b;
}</p>
3. 编译生成DLL
构建项目后,Visual Studio会生成两个关键文件:
- MyMathLib.dll:动态链接库文件
- MyMathLib.lib:导入库(用于链接)
在另一个程序中使用DLL
你可以通过隐式链接(运行时自动加载)或显式加载(手动调用)的方式使用DLL。
方法一:隐式链接(推荐初学者)
需要DLL、.lib 文件和头文件。
新建一个C++控制台应用程序,包含以下步骤:
- 将 MathFunctions.h 复制到项目中
- 将 MyMathLib.lib 添加到项目依赖(右键项目 → 属性 → 链接器 → 输入 → 附加依赖项)
- 把 MyMathLib.dll 放在可执行文件(.exe)同一目录下
使用示例代码:
#include <iostream>
#include "MathFunctions.h"
<p>int main() {
std::cout << "Add: " << Add(5, 3) << std::endl;
std::cout << "Multiply: " << Multiply(4, 7) << std::endl;
return 0;
}</p>
方法二:显式加载(使用 LoadLibrary)
不需要 .lib 文件,运行时手动加载函数地址。
示例代码:
#include <iostream>
#include <windows.h>
<p>typedef int (<em>AddFunc)(int, int);
typedef int (</em>MultiplyFunc)(int, int);</p><p>int main() {
HINSTANCE hDll = LoadLibrary(L"MyMathLib.dll");
if (!hDll) {
std::cout << "无法加载DLL" << std::endl;
return 1;
}</p><pre class='brush:php;toolbar:false;'>AddFunc Add = (AddFunc)GetProcAddress(hDll, "Add");
MultiplyFunc Multiply = (MultiplyFunc)GetProcAddress(hDll, "Multiply");
if (Add && Multiply) {
std::cout << "Add: " << Add(5, 3) << std::endl;
std::cout << "Multiply: " << Multiply(4, 7) << std::endl;
} else {
std::cout << "无法获取函数地址" << std::endl;
}
FreeLibrary(hDll);
return 0;
}
立即学习“C++免费学习笔记(深入)”;
注意事项与最佳实践
编写DLL时注意以下几点:
- 使用 extern "C" 防止C++函数名修饰(mangling),便于其他语言调用
- DLL应尽量避免导出C++类(除非使用者也使用相同编译器和设置)
- 确保运行时环境有对应版本的C++运行库(如MSVCRT)
- 发布DLL时,同时提供头文件和.lib(如使用隐式链接)
基本上就这些。掌握DLL的创建和调用是Windows平台C++开发的重要技能,尤其在大型项目或组件复用中非常实用。不复杂但容易忽略细节,比如路径、导出符号和运行时依赖。










