使用pip install -e能否避免C++扩展模块从头编译?
让
pip install -e保留CMake增量编译缓存的解决方案 问题根源
pip install -e .默认会在隔离的临时构建目录中执行编译流程,不会复用项目目录下的CMakeCache.txt和依赖追踪文件;而python setup.py develop是直接在项目目录内完成构建,因此能保留CMake的增量编译缓存。同时,直接调用setup.py会忽略pyproject.toml的配置,这是因为现代Python包构建规范要求通过pip或符合PEP 517的工具调用构建流程,而非直接执行setup.py。
解决方案
1. 修改setup.py,指定CMake在项目内生成构建文件
核心思路是让CMake在项目目录下固定的子目录(比如./cmake-build)中生成缓存和构建产物,而非临时目录。示例代码如下:
from setuptools import setup, Extension from setuptools.command.build_ext import build_ext import os import sys import subprocess class CMakeExtension(Extension): def __init__(self, name, sourcedir=""): Extension.__init__(self, name, sources=[]) self.sourcedir = os.path.abspath(sourcedir) class CMakeBuild(build_ext): def build_extension(self, ext): # 确定扩展模块的输出目录 extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name))) # 指定项目内的CMake构建目录 cmake_build_dir = os.path.join(os.getcwd(), "cmake-build") os.makedirs(cmake_build_dir, exist_ok=True) # 配置CMake参数 cmake_args = [ f"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={extdir}", f"-DPYTHON_EXECUTABLE={sys.executable}", # 添加你的其他CMake编译参数,比如依赖路径、编译选项等 ] # 执行CMake配置 subprocess.check_call(["cmake", ext.sourcedir] + cmake_args, cwd=cmake_build_dir) # 执行构建 subprocess.check_call(["cmake", "--build", ".", "--config", "Release"], cwd=cmake_build_dir) setup( name="your-libigl-module", version="0.1.0", ext_modules=[CMakeExtension("your_extension")], cmdclass={"build_ext": CMakeBuild}, # 补充其他包配置信息,比如作者、描述等 )
2. 正确配置pyproject.toml
确保pyproject.toml符合PEP 517规范,让pip识别构建依赖和后端,避免忽略配置:
[build-system] requires = ["setuptools>=61.0", "cmake>=3.18", "pybind11>=2.6"] build-backend = "setuptools.build_meta"
3. 可选:使用--no-build-isolation参数
如果不想修改setup.py,可以尝试执行:
python -m pip install -e . --no-build-isolation
该参数会让pip在当前环境中执行构建,而非创建隔离环境,从而复用项目内已有的CMake缓存。但这种方式可能因环境依赖冲突引发问题,仅作为临时替代方案。
注意事项
- 将
cmake-build目录添加到.gitignore中,避免提交构建产物和缓存文件。 - 需要完全重新构建时,手动删除
cmake-build目录即可。
内容的提问来源于stack exchange,提问作者Alec Jacobson
相关产品推荐
相关产品推荐

