Blame external/pybind11/docs/compiling.rst

Packit 534379
.. _compiling:
Packit 534379
Packit 534379
Build systems
Packit 534379
#############
Packit 534379
Packit 534379
Building with setuptools
Packit 534379
========================
Packit 534379
Packit 534379
For projects on PyPI, building with setuptools is the way to go. Sylvain Corlay
Packit 534379
has kindly provided an example project which shows how to set up everything,
Packit 534379
including automatic generation of documentation using Sphinx. Please refer to
Packit 534379
the [python_example]_ repository.
Packit 534379
Packit 534379
.. [python_example] https://github.com/pybind/python_example
Packit 534379
Packit 534379
Building with cppimport
Packit 534379
========================
Packit 534379
Packit 534379
[cppimport]_ is a small Python import hook that determines whether there is a C++
Packit 534379
source file whose name matches the requested module. If there is, the file is
Packit 534379
compiled as a Python extension using pybind11 and placed in the same folder as
Packit 534379
the C++ source file. Python is then able to find the module and load it.
Packit 534379
Packit 534379
.. [cppimport] https://github.com/tbenthompson/cppimport
Packit 534379
Packit 534379
.. _cmake:
Packit 534379
Packit 534379
Building with CMake
Packit 534379
===================
Packit 534379
Packit 534379
For C++ codebases that have an existing CMake-based build system, a Python
Packit 534379
extension module can be created with just a few lines of code:
Packit 534379
Packit 534379
.. code-block:: cmake
Packit 534379
Packit 534379
    cmake_minimum_required(VERSION 2.8.12)
Packit 534379
    project(example)
Packit 534379
Packit 534379
    add_subdirectory(pybind11)
Packit 534379
    pybind11_add_module(example example.cpp)
Packit 534379
Packit 534379
This assumes that the pybind11 repository is located in a subdirectory named
Packit 534379
:file:`pybind11` and that the code is located in a file named :file:`example.cpp`.
Packit 534379
The CMake command ``add_subdirectory`` will import the pybind11 project which
Packit 534379
provides the ``pybind11_add_module`` function. It will take care of all the
Packit 534379
details needed to build a Python extension module on any platform.
Packit 534379
Packit 534379
A working sample project, including a way to invoke CMake from :file:`setup.py` for
Packit 534379
PyPI integration, can be found in the [cmake_example]_  repository.
Packit 534379
Packit 534379
.. [cmake_example] https://github.com/pybind/cmake_example
Packit 534379
Packit 534379
pybind11_add_module
Packit 534379
-------------------
Packit 534379
Packit 534379
To ease the creation of Python extension modules, pybind11 provides a CMake
Packit 534379
function with the following signature:
Packit 534379
Packit 534379
.. code-block:: cmake
Packit 534379
Packit 534379
    pybind11_add_module(<name> [MODULE | SHARED] [EXCLUDE_FROM_ALL]
Packit 534379
                        [NO_EXTRAS] [SYSTEM] [THIN_LTO] source1 [source2 ...])
Packit 534379
Packit 534379
This function behaves very much like CMake's builtin ``add_library`` (in fact,
Packit 534379
it's a wrapper function around that command). It will add a library target
Packit 534379
called ``<name>`` to be built from the listed source files. In addition, it
Packit 534379
will take care of all the Python-specific compiler and linker flags as well
Packit 534379
as the OS- and Python-version-specific file extension. The produced target
Packit 534379
``<name>`` can be further manipulated with regular CMake commands.
Packit 534379
Packit 534379
``MODULE`` or ``SHARED`` may be given to specify the type of library. If no
Packit 534379
type is given, ``MODULE`` is used by default which ensures the creation of a
Packit 534379
Python-exclusive module. Specifying ``SHARED`` will create a more traditional
Packit 534379
dynamic library which can also be linked from elsewhere. ``EXCLUDE_FROM_ALL``
Packit 534379
removes this target from the default build (see CMake docs for details).
Packit 534379
Packit 534379
Since pybind11 is a template library, ``pybind11_add_module`` adds compiler
Packit 534379
flags to ensure high quality code generation without bloat arising from long
Packit 534379
symbol names and duplication of code in different translation units. It
Packit 534379
sets default visibility to *hidden*, which is required for some pybind11
Packit 534379
features and functionality when attempting to load multiple pybind11 modules
Packit 534379
compiled under different pybind11 versions.  It also adds additional flags
Packit 534379
enabling LTO (Link Time Optimization) and strip unneeded symbols. See the
Packit 534379
:ref:`FAQ entry <faq:symhidden>` for a more detailed explanation. These
Packit 534379
latter optimizations are never applied in ``Debug`` mode.  If ``NO_EXTRAS`` is
Packit 534379
given, they will always be disabled, even in ``Release`` mode. However, this
Packit 534379
will result in code bloat and is generally not recommended.
Packit 534379
Packit 534379
By default, pybind11 and Python headers will be included with ``-I``. In order
Packit 534379
to include pybind11 as system library, e.g. to avoid warnings in downstream
Packit 534379
code with warn-levels outside of pybind11's scope, set the option ``SYSTEM``.
Packit 534379
Packit 534379
As stated above, LTO is enabled by default. Some newer compilers also support
Packit 534379
different flavors of LTO such as `ThinLTO`_. Setting ``THIN_LTO`` will cause
Packit 534379
the function to prefer this flavor if available. The function falls back to
Packit 534379
regular LTO if ``-flto=thin`` is not available.
Packit 534379
Packit 534379
.. _ThinLTO: http://clang.llvm.org/docs/ThinLTO.html
Packit 534379
Packit 534379
Configuration variables
Packit 534379
-----------------------
Packit 534379
Packit 534379
By default, pybind11 will compile modules with the C++14 standard, if available
Packit 534379
on the target compiler, falling back to C++11 if C++14 support is not
Packit 534379
available.  Note, however, that this default is subject to change: future
Packit 534379
pybind11 releases are expected to migrate to newer C++ standards as they become
Packit 534379
available.  To override this, the standard flag can be given explicitly in
Packit 534379
``PYBIND11_CPP_STANDARD``:
Packit 534379
Packit 534379
.. code-block:: cmake
Packit 534379
Packit 534379
    # Use just one of these:
Packit 534379
    # GCC/clang:
Packit 534379
    set(PYBIND11_CPP_STANDARD -std=c++11)
Packit 534379
    set(PYBIND11_CPP_STANDARD -std=c++14)
Packit 534379
    set(PYBIND11_CPP_STANDARD -std=c++1z) # Experimental C++17 support
Packit 534379
    # MSVC:
Packit 534379
    set(PYBIND11_CPP_STANDARD /std:c++14)
Packit 534379
    set(PYBIND11_CPP_STANDARD /std:c++latest) # Enables some MSVC C++17 features
Packit 534379
Packit 534379
    add_subdirectory(pybind11)  # or find_package(pybind11)
Packit 534379
Packit 534379
Note that this and all other configuration variables must be set **before** the
Packit 534379
call to ``add_subdirectory`` or ``find_package``. The variables can also be set
Packit 534379
when calling CMake from the command line using the ``-D<variable>=<value>`` flag.
Packit 534379
Packit 534379
The target Python version can be selected by setting ``PYBIND11_PYTHON_VERSION``
Packit 534379
or an exact Python installation can be specified with ``PYTHON_EXECUTABLE``.
Packit 534379
For example:
Packit 534379
Packit 534379
.. code-block:: bash
Packit 534379
Packit 534379
    cmake -DPYBIND11_PYTHON_VERSION=3.6 ..
Packit 534379
    # or
Packit 534379
    cmake -DPYTHON_EXECUTABLE=path/to/python ..
Packit 534379
Packit 534379
find_package vs. add_subdirectory
Packit 534379
---------------------------------
Packit 534379
Packit 534379
For CMake-based projects that don't include the pybind11 repository internally,
Packit 534379
an external installation can be detected through ``find_package(pybind11)``.
Packit 534379
See the `Config file`_ docstring for details of relevant CMake variables.
Packit 534379
Packit 534379
.. code-block:: cmake
Packit 534379
Packit 534379
    cmake_minimum_required(VERSION 2.8.12)
Packit 534379
    project(example)
Packit 534379
Packit 534379
    find_package(pybind11 REQUIRED)
Packit 534379
    pybind11_add_module(example example.cpp)
Packit 534379
Packit 534379
Note that ``find_package(pybind11)`` will only work correctly if pybind11
Packit 534379
has been correctly installed on the system, e. g. after downloading or cloning
Packit 534379
the pybind11 repository  :
Packit 534379
Packit 534379
.. code-block:: bash
Packit 534379
Packit 534379
    cd pybind11
Packit 534379
    mkdir build
Packit 534379
    cd build
Packit 534379
    cmake ..
Packit 534379
    make install
Packit 534379
Packit 534379
Once detected, the aforementioned ``pybind11_add_module`` can be employed as
Packit 534379
before. The function usage and configuration variables are identical no matter
Packit 534379
if pybind11 is added as a subdirectory or found as an installed package. You
Packit 534379
can refer to the same [cmake_example]_ repository for a full sample project
Packit 534379
-- just swap out ``add_subdirectory`` for ``find_package``.
Packit 534379
Packit 534379
.. _Config file: https://github.com/pybind/pybind11/blob/master/tools/pybind11Config.cmake.in
Packit 534379
Packit 534379
Advanced: interface library target
Packit 534379
----------------------------------
Packit 534379
Packit 534379
When using a version of CMake greater than 3.0, pybind11 can additionally
Packit 534379
be used as a special *interface library* . The target ``pybind11::module``
Packit 534379
is available with pybind11 headers, Python headers and libraries as needed,
Packit 534379
and C++ compile definitions attached. This target is suitable for linking
Packit 534379
to an independently constructed (through ``add_library``, not
Packit 534379
``pybind11_add_module``) target in the consuming project.
Packit 534379
Packit 534379
.. code-block:: cmake
Packit 534379
Packit 534379
    cmake_minimum_required(VERSION 3.0)
Packit 534379
    project(example)
Packit 534379
Packit 534379
    find_package(pybind11 REQUIRED)  # or add_subdirectory(pybind11)
Packit 534379
Packit 534379
    add_library(example MODULE main.cpp)
Packit 534379
    target_link_libraries(example PRIVATE pybind11::module)
Packit 534379
    set_target_properties(example PROPERTIES PREFIX "${PYTHON_MODULE_PREFIX}"
Packit 534379
                                             SUFFIX "${PYTHON_MODULE_EXTENSION}")
Packit 534379
Packit 534379
.. warning::
Packit 534379
Packit 534379
    Since pybind11 is a metatemplate library, it is crucial that certain
Packit 534379
    compiler flags are provided to ensure high quality code generation. In
Packit 534379
    contrast to the ``pybind11_add_module()`` command, the CMake interface
Packit 534379
    library only provides the *minimal* set of parameters to ensure that the
Packit 534379
    code using pybind11 compiles, but it does **not** pass these extra compiler
Packit 534379
    flags (i.e. this is up to you).
Packit 534379
Packit 534379
    These include Link Time Optimization (``-flto`` on GCC/Clang/ICPC, ``/GL``
Packit 534379
    and ``/LTCG`` on Visual Studio) and .OBJ files with many sections on Visual
Packit 534379
    Studio (``/bigobj``).  The :ref:`FAQ <faq:symhidden>` contains an
Packit 534379
    explanation on why these are needed.
Packit 534379
Packit 534379
Embedding the Python interpreter
Packit 534379
--------------------------------
Packit 534379
Packit 534379
In addition to extension modules, pybind11 also supports embedding Python into
Packit 534379
a C++ executable or library. In CMake, simply link with the ``pybind11::embed``
Packit 534379
target. It provides everything needed to get the interpreter running. The Python
Packit 534379
headers and libraries are attached to the target. Unlike ``pybind11::module``,
Packit 534379
there is no need to manually set any additional properties here. For more
Packit 534379
information about usage in C++, see :doc:`/advanced/embedding`.
Packit 534379
Packit 534379
.. code-block:: cmake
Packit 534379
Packit 534379
    cmake_minimum_required(VERSION 3.0)
Packit 534379
    project(example)
Packit 534379
Packit 534379
    find_package(pybind11 REQUIRED)  # or add_subdirectory(pybind11)
Packit 534379
Packit 534379
    add_executable(example main.cpp)
Packit 534379
    target_link_libraries(example PRIVATE pybind11::embed)
Packit 534379
Packit 534379
.. _building_manually:
Packit 534379
Packit 534379
Building manually
Packit 534379
=================
Packit 534379
Packit 534379
pybind11 is a header-only library, hence it is not necessary to link against
Packit 534379
any special libraries and there are no intermediate (magic) translation steps.
Packit 534379
Packit 534379
On Linux, you can compile an example such as the one given in
Packit 534379
:ref:`simple_example` using the following command:
Packit 534379
Packit 534379
.. code-block:: bash
Packit 534379
Packit 534379
    $ c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`
Packit 534379
Packit 534379
The flags given here assume that you're using Python 3. For Python 2, just
Packit 534379
change the executable appropriately (to ``python`` or ``python2``).
Packit 534379
Packit 534379
The ``python3 -m pybind11 --includes`` command fetches the include paths for
Packit 534379
both pybind11 and Python headers. This assumes that pybind11 has been installed
Packit 534379
using ``pip`` or ``conda``. If it hasn't, you can also manually specify
Packit 534379
``-I <path-to-pybind11>/include`` together with the Python includes path
Packit 534379
``python3-config --includes``.
Packit 534379
Packit 534379
Note that Python 2.7 modules don't use a special suffix, so you should simply
Packit 534379
use ``example.so`` instead of ``example`python3-config --extension-suffix```.
Packit 534379
Besides, the ``--extension-suffix`` option may or may not be available, depending
Packit 534379
on the distribution; in the latter case, the module extension can be manually
Packit 534379
set to ``.so``.
Packit 534379
Packit 534379
On Mac OS: the build command is almost the same but it also requires passing
Packit 534379
the ``-undefined dynamic_lookup`` flag so as to ignore missing symbols when
Packit 534379
building the module:
Packit 534379
Packit 534379
.. code-block:: bash
Packit 534379
Packit 534379
    $ c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`
Packit 534379
Packit 534379
In general, it is advisable to include several additional build parameters
Packit 534379
that can considerably reduce the size of the created binary. Refer to section
Packit 534379
:ref:`cmake` for a detailed example of a suitable cross-platform CMake-based
Packit 534379
build system that works on all platforms including Windows.
Packit 534379
Packit 534379
.. note::
Packit 534379
Packit 534379
    On Linux and macOS, it's better to (intentionally) not link against
Packit 534379
    ``libpython``. The symbols will be resolved when the extension library
Packit 534379
    is loaded into a Python binary. This is preferable because you might
Packit 534379
    have several different installations of a given Python version (e.g. the
Packit 534379
    system-provided Python, and one that ships with a piece of commercial
Packit 534379
    software). In this way, the plugin will work with both versions, instead
Packit 534379
    of possibly importing a second Python library into a process that already
Packit 534379
    contains one (which will lead to a segfault).
Packit 534379
Packit 534379
Generating binding code automatically
Packit 534379
=====================================
Packit 534379
Packit 534379
The ``Binder`` project is a tool for automatic generation of pybind11 binding
Packit 534379
code by introspecting existing C++ codebases using LLVM/Clang. See the
Packit 534379
[binder]_ documentation for details.
Packit 534379
Packit 534379
.. [binder] http://cppbinder.readthedocs.io/en/latest/about.html