You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何彻底解决Pybind11导入模块时的DLL缺失错误?

解决MinGW编译Pybind11模块的DLL加载失败与静态链接问题

编译完Pybind11模块后,导入时出现以下错误:
ImportError: DLL load failed while importing test_module: The specified module could not be found.

临时添加MinGW的C:/msys64/mingw64/bin目录到系统PATH可以解决,但这个方案无法直接分发模块给没有MinGW环境的用户。以下是彻底解决的可行方法:

现有代码

模块的C++实现:

#include <iostream>
#include <pybind11/pybind11.h>

void sayHello() {
  std::cout << "Hello World!\n";
}

PYBIND11_MODULE(test_module, m) {
  m.doc() = "This is momumental!";
  m.def("sayHello", &sayHello, "Function that prints Hello World");
}

CMake配置:

cmake_minimum_required(VERSION 3.10)
project("test_module")

set(EXECUTABLE_OUTPUT_PATH "../")
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
add_subdirectory(".extern/pybind11")

pybind11_add_module("test_module" main.cpp)
target_compile_options("test_module" PRIVATE "-static-libgcc" "-static-libstdc++")

解决方案

1. 补全静态链接选项

你当前只链接了GCC和C++标准库的静态版本,但MinGW编译的模块通常还依赖libwinpthread-1.dll,需要把这个库也静态链接进去。修改CMake的链接选项:

# 替换原有的target_compile_options,改用target_link_options更准确
target_link_options("test_module" PRIVATE "-static-libgcc" "-static-libstdc++" "-static-libwinpthread")

# 或者直接使用全静态链接(适合分发,但注意部分系统库无法静态链接,不影响)
# target_link_options("test_module" PRIVATE "-static")

2. 准确排查缺失的DLL

用MinGW自带的ldd工具(在MSYS2终端中运行)检查模块的依赖:

ldd test_module.cp310-win_amd64.pyd  # 替换成你的模块文件名

输出中除了系统DLL(比如kernel32.dll、user32.dll)之外的条目,就是需要静态链接的依赖库,针对性添加静态链接选项即可。

3. 确保Python ABI兼容性

  • 确认编译模块用的MinGW版本(32/64位)和运行的Python版本一致;
  • 如果使用官方CPython,建议用对应版本的MinGW编译(比如CPython 3.10对应MinGW-w64 8.x及以上版本)。

4. 正确生成CMake构建文件

运行CMake时指定MinGW Makefiles生成器,避免和其他编译环境冲突:

cmake -G "MinGW Makefiles" -B build .
cmake --build build

通过以上步骤,模块会将所有必要的依赖静态链接到Pyd文件中,无需依赖用户环境中的MinGW DLL即可直接导入使用。

内容的提问来源于stack exchange,提问作者Tyler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 10:55:16