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

在Windows平台上,使用C++编写动态链接库(DLL)是一种常见的模块化编程方式。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会生成两个关键文件:
你可以通过隐式链接(运行时自动加载)或显式加载(手动调用)的方式使用DLL。
方法一:隐式链接(推荐初学者)
需要DLL、.lib 文件和头文件。
新建一个C++控制台应用程序,包含以下步骤:
使用示例代码:
#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时注意以下几点:
基本上就这些。掌握DLL的创建和调用是Windows平台C++开发的重要技能,尤其在大型项目或组件复用中非常实用。不复杂但容易忽略细节,比如路径、导出符号和运行时依赖。
以上就是C++如何编写一个动态链接库(DLL)_C++在Windows平台创建和使用DLL的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号