.. _use_cmake_integration: Use CMake integration [Recommended] ==================================== Generate Python Bindings and Compile the Module ............................................... To generate the Python bindings and compile the module with CMake, we simply run .. code-block:: bash $ mkdir build $ cd build $ cmake .. $ make -j 8 CMake Configuration ................... The ``CMakeLists.txt`` used for our :ref:`getting_started` example looks as follows: .. literalinclude:: ../examples/getting_started/CMakeLists.txt :language: cmake :linenos: Let's take a closer look at the ``CMakeLists.txt`` file: * **[Lines 1-5]** Standard CMake project configuration where we require ``c++20`` support and tell CMake to generate a ``compile_commands.json`` database file. * **[Lines 8]** Since we want to build a Python C++ extension, we need to find Python/Numpy on the system. * **[Lines 11-17]** We fetch **c2py** from GitHub and make it available for the current project rather than relying on a system installation. This ensures that both, **c2py** and the extension module, iare built with consistent compiler options and linked against the same Python interpreter. As **c2py** compiles quickly, it does not add significant overhead to the build process. * **[Lines 20–21]** We use the ``Python_add_library`` command to declare our ``getting_started`` extension module. The command is part of `CMake `_. * **[Line 27-end]** Here we introduce the user option ``Update_Python_Bindings`` and, if it is set to ``ON``, we call the ``clair_c2py_generate_bindings`` macro provided by **c2py**. The macro finds the ``clair-c2py`` executable and makes sure to (re)generate the bindings before the module is compiled. .. note:: * The bindings are only (re)generated if the option ``Update_Python_Bindings`` is set to ``ON``. * ``clair-c2py`` automatically uses the compilation database generated by CMake. * Even if CMake uses an out-of-source build, the tools acts **in the source directory**, where it generates the binding files. General Workflow ................ The above ``CMakeLists.txt`` file is designed to be used in two different modes, depending on the value of the ``Update_Python_Bindings`` option: * **Developer Mode** (``Update_Python_Bindings == ON``)[default]: * The bindings are automatically regenerated using ``clair-c2py`` when the C++ code or the options TOML file are modified. * At the end, the regenerated bindings should be committed along with the rest of the source (they are produced in the **source** directory). * Any C++20-compliant compiler can be used to compile the module, even though ``clair-c2py`` itself relies on Clang and its libraries. * **User Mode** (``Update_Python_Bindings == OFF``): * The compilation uses the bindings already present in the source, as they are included in ``my_module.cpp``. * ``clair-c2py`` and **clair** in general are not needed. * Any C++20-compliant compiler can be used.