Setuptools extension to build and package CMake projects
cmake-build-extension is a Setuptools extension designed to simplify the integration of C++ projects based on CMake with Python packaging tools. It enables configuring and building CMake projects directly from `setup.py`, installing their artifacts into the resulting Python package, and passing custom CMake options. The library also provides a context manager for reliable CPython module imports across operating systems. It is currently at version 0.6.1, with releases occurring on an as-needed basis for features and bug fixes.
Warnings
- breaking Support for Python 3.6 was removed in version 0.6.0. Projects targeting Python 3.6 will need to stay on an older version of cmake-build-extension or upgrade their Python environment.
- gotcha When developing with C++ extensions, ensure your CMake project configuration (e.g., `CMAKE_BUILD_TYPE`, generator selection) is correctly handled. Version 0.6.0 improved how users can specify the desired CMake generator, which might affect existing setups.
- gotcha It is crucial for CMake-based projects to perform out-of-source builds to avoid polluting the source directory and prevent build issues. While `cmake-build-extension` handles this, accidentally running CMake directly in the source directory can lead to problems.
- gotcha If your CMake project exports targets or has complex C++ dependencies, downstream Python projects might need to extend their `CMAKE_MODULE_PATH` or use `cmake-build-extension`'s `cmake_depends_on` option. Packaging shared C++ libraries also needs careful consideration for `manylinux` compatibility on Linux.
Install
-
pip install cmake-build-extension
Imports
- BuildExtension
from cmake_build_extension import BuildExtension
- CMakeExtension
from cmake_build_extension import CMakeExtension
Quickstart
from setuptools import setup, find_packages
from cmake_build_extension import BuildExtension, CMakeExtension
# --- Minimal Example setup.py ---
# This assumes a C++ project structured like:
# myproject/
# |-- CMakeLists.txt
# |-- src/my_cpp_lib.cpp
# |-- python/
# `-- my_python_package/
# `-- __init__.py
setup(
name="my-hybrid-package",
version="0.1.0",
packages=find_packages(where="python"),
package_dir={'': "python"},
ext_modules=[
CMakeExtension(
name="MyProject", # Corresponds to a CMake target or project name
install_prefix="my_python_package", # Where to install CMake artifacts within the Python package
cmake_configure_options=[
"-DBUILD_SHARED_LIBS=ON",
# Additional CMake options can be passed here
],
# Optional: Specify a CMake component to install
# cmake_install_component="my_component",
),
],
cmdclass=dict(build_ext=BuildExtension),
zip_safe=False, # Often required for packages containing C extensions
)