0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【備忘録】CMakeLists.txt と setup.py / pyproject.toml の関係

Posted at

CMakeLists.txt と setup.py / pyproject.toml の関係

C++ライブラリをPythonパッケージ化する流れがよくわかっていなかったので、調べたことを踏まえ備忘録(雑多なメモ with GPT5)。
C++/Python混在プロジェクトで拡張モジュールを配布したい人にも役立つとなお良い。


1. CMakeLists.txt とは?

  • C++プロジェクトのビルドレシピファイル。
  • ソースコードを「どうコンパイルしてライブラリや実行ファイルにするか」を記述する。

2. setup.py / pyproject.toml とは?

  • Pythonパッケージのビルドレシピファイル。
  • パッケージ名・依存関係・ビルド方法を定義する。
観点 CMakeLists.txt(C++) setup.py / pyproject.toml(Python)
目的 C/C++ プロジェクトのビルドレシピ Python パッケージのビルドレシピ
置き場所 プロジェクトのルートに CMakeLists.txt プロジェクトのルートに setup.py または pyproject.toml
主な役割 ソースをライブラリ/実行ファイルにする Pythonパッケージにする
依存関係 find_package(OpenCV REQUIRED) など install_requires, dependencies
バージョン指定 cmake_minimum_required(VERSION 3.15) requires = [...]
実行例 cmake .. && make pip install .

3. 両者を組み合わせる流れ

ステップ1: CMakeLists.txt 側

cmake_minimum_required(VERSION 3.15)
project(my_cpp_module LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)

# pybind11を探してリンク
find_package(pybind11 REQUIRED)

pybind11_add_module(my_cpp_module src/module.cpp)

👉 ここで Python から呼べる拡張モジュール(my_cpp_module.so)を生成。


ステップ2: setup.py を使う場合(従来型)

from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
import subprocess

class CMakeBuild(build_ext):
    def build_extension(self, ext):
        subprocess.check_call(["cmake", ".", "-Bbuild"])
        subprocess.check_call(["cmake", "--build", "build"])

setup(
    name="my_cpp_module",
    version="0.1",
    ext_modules=[Extension("my_cpp_module", sources=[])],
    cmdclass={"build_ext": CMakeBuild},
)

ステップ3: pyproject.toml を使う場合(モダン)

[build-system]
requires = ["setuptools>=42", "wheel", "scikit-build-core", "pybind11"]
build-backend = "setuptools.build_meta"

[project]
name = "my_cpp_module"
version = "0.1.0"
description = "C++ library wrapped for Python using pybind11"

👉 pip install . するだけで CMake → Python パッケージ化まで自動化できる。


4. まとめ

  • CMakeLists.txt は C++ビルドを担当。
  • setup.py / pyproject.toml は Pythonパッケージ化を担当。
  • 両者を組み合わせることで「C++の高速処理をPythonから呼び出せる」ようになる。
  • 最近は pyproject.toml + scikit-build-core が主流。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?