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

Windows 11下Python调用C程序崩溃,返回STATUS_DLL_NOT_FOUND错误

解决Windows 11下Python subprocess调用MinGW编译程序返回STATUS_DLL_NOT_FOUND的问题

问题背景

在Windows 11系统中,使用Python的subprocess.run()调用MinGW编译的C程序时,返回错误码3221225781(对应STATUS_DLL_NOT_FOUND),但直接运行该程序可正常输出。已尝试用gcc -static -static-libgcc -o test.exe test.c静态编译,问题仍存在。

相关代码:

test.c

#include <stdio.h>

int main() {
   printf("Hello World!");
   return 0;
}

test.py

import subprocess

if __name__ == '__main__':
    prog = "./test.exe"
    result = subprocess.run(prog)
    print(result)

解决方案

1. 完善编译参数,静态链接所有依赖库

MinGW的-static参数无法自动覆盖所有依赖库的静态链接,需补充完整参数:

gcc -static -static-libgcc -static-libstdc++ -static-libwinpthread -o test.exe test.c
  • -static-libgcc:静态链接GCC的C运行时库
  • -static-libstdc++:静态链接C++标准库(部分MinGW版本即使编译C程序也会依赖该库)
  • -static-libwinpthread:静态链接Win32线程库,避免依赖winpthread.dll

2. 修正Python中的程序路径

Windows环境下,相对路径./test.exe可能因Python工作目录与脚本目录不一致导致加载失败,建议使用绝对路径:

import subprocess
import os

if __name__ == '__main__':
    # 获取脚本所在目录的绝对路径
    script_dir = os.path.dirname(os.path.abspath(__file__))
    prog_path = os.path.join(script_dir, "test.exe")
    # 捕获输出便于排查问题
    result = subprocess.run(prog_path, capture_output=True, text=True)
    print("返回码:", result.returncode)
    print("程序输出:", result.stdout)
    print("错误信息:", result.stderr)

3. 检查Python与编译程序的位数兼容性

确保Python和编译的test.exe位数一致:

  • 64位Python对应64位MinGW编译程序
  • 32位Python对应32位MinGW编译程序
    可通过以下代码查看Python位数:
import sys
print(sys.maxsize > 2**32)  # 输出True为64位,False为32位

4. 排查剩余依赖DLL

使用工具定位未静态链接的依赖:

  • Dependency Walker:直接打开test.exe,查看红色标记的缺失DLL
  • Process Monitor:过滤test.exe的文件操作,追踪找不到的DLL路径

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 17:15:13