在Windows下使用setup.py为Pybind11指定MinGW编译器
如何在Windows下通过setuptools指定MinGW编译Pybind11扩展
在Windows环境中使用setuptools的setup.py编译基于Pybind11的C扩展时,系统默认会采用MSVC编译器。但如果代码依赖仅GNU环境支持的stdlibc,就需要强制指定使用MinGW编译器。以下是具体实现方法:
前置准备
- 确保已安装MinGW-w64,并将MinGW的
bin目录(例如C:\mingw64\bin)添加到系统环境变量PATH的最前端,保证系统优先识别MinGW的gcc/g++。
修改setup.py配置
需要在setup.py中添加编译器指定逻辑,强制使用MinGW工具链,同时适配链接器参数:
修改后的setup.py代码:
""" python setup.py install """ from pybind11.setup_helpers import Pybind11Extension from setuptools import setup import setuptools import os import shutil # 强制指定MinGW编译器 os.environ['CC'] = 'gcc' os.environ['CXX'] = 'g++' ext_modules = [ Pybind11Extension( 'check_compiler', sources=['check_compiler.cpp'], language='c++', cxx_std=11, # 添加MinGW编译所需的额外参数 extra_compile_args=['-std=c++11', '-static-libgcc', '-static-libstdc++'], extra_link_args=['-static-libgcc', '-static-libstdc++'] ), ] # 覆盖默认链接器,使用MinGW的g++ class BuildExtOverride(setuptools.command.build_ext.build_ext): def build_extensions(self): self.compiler.linker_exe = 'g++' super().build_extensions() setup( name='check_compiler', author='XXX', ext_modules=ext_modules, cmdclass={'build_ext': BuildExtOverride} ) # copy the package for filename in os.listdir("dist"): if filename.endswith(".egg"): shutil.copy(os.path.join("dist", filename), ".")
关键配置说明
- 通过
os.environ['CC']和os.environ['CXX']强制指定C/C编译器为MinGW的gcc/g extra_compile_args和extra_link_args添加静态链接参数,避免运行时依赖MinGW动态库- 自定义
BuildExtOverride类替换默认链接器,确保使用g++而非MSVC的link.exe
编译与测试
- 执行编译命令:
python setup.py install
- 运行测试脚本
main.py:
import check_compiler check_compiler.test()
若输出Not compiled with MSVC.,说明已成功使用MinGW编译器完成编译。
内容的提问来源于stack exchange,提问作者Jerry
相关产品推荐
相关产品推荐

