.. _cmake: CMake Integration ----------------- Let us consider a simple piece of C++ code: .. literalinclude:: examples/cmake3/my_module.cpp :language: cpp CMake configuration ................... A complete CMake configuration file for this module is: .. literalinclude:: examples/cmake3/CMakeLists.txt :language: cmake :linenos: Brief explanation of the CMake file: * **[Lines 1–19]** This section provides a standard CMake configuration for building a Python C++ extension. The ``Python_add_library`` command declares the extension using CMake’s `FindPython `_ module. - Note that the ``c2py`` library is fetched and linked to the module (rather than using any installed version of ``c2py``). This approach is recommended, since it ensures that both the module and ``c2py`` are 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. * **[Line 23-end]** This is the ``clair-c2py`` specific part, which is trigged if the option ``Update_Python_Bindings`` is set to ``ON``: #. Find the ``clair-c2py`` executable. #. Regenerate the bindings before compiling the module. .. note:: * ``clair-c2py`` automatically uses the `compile_commands.json` file generated by CMake for the file ``my_module.cpp`` to detect all include flags from the project's linked libraries (targets). * The ``-p`` option is used to specify the path to the `compile_commands.json` file (in the build directory). * However the tools acts **in the source directory**, producing some additional ``.cxx`` source files. * An additionnal ``my_module.wrap.hxx`` file is also generated, only used in multiple module situations, cf :ref:`multiple_modules`. Compiling ......... To compile the module, run the following commands: .. code-block:: bash $ mkdir build $ cd build $ cmake .. -DUpdate_Python_Bindings=ON $ make -j 8 You can then use the module in Python: .. code-block:: console >>> import my_module as M >>> a = M.MyClass(1, 2) >>> a.f(3) 4 Workflow ........ This ``CMakeLists.txt`` file is designed to be used in two different modes, depending on the value of the ``Update_Python_Bindings`` option: * **User Mode** (``Update_Python_Bindings == OFF``) [default]: * The compilation uses the bindings already present in the source, as they are included in ``my_module.cpp``. * ``clair-c2py`` is not required. * Any C++20-compliant compiler can be used. * **Developer Mode** (``Update_Python_Bindings == ON``): * 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 still be used to compile the module, even though ``clair-c2py`` itself relies on Clang and its libraries.