compiling.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. .. _compiling:
  2. Build systems
  3. #############
  4. Building with setuptools
  5. ========================
  6. For projects on PyPI, building with setuptools is the way to go. Sylvain Corlay
  7. has kindly provided an example project which shows how to set up everything,
  8. including automatic generation of documentation using Sphinx. Please refer to
  9. the [python_example]_ repository.
  10. .. [python_example] https://github.com/pybind/python_example
  11. Building with cppimport
  12. ========================
  13. [cppimport]_ is a small Python import hook that determines whether there is a C++
  14. source file whose name matches the requested module. If there is, the file is
  15. compiled as a Python extension using pybind11 and placed in the same folder as
  16. the C++ source file. Python is then able to find the module and load it.
  17. .. [cppimport] https://github.com/tbenthompson/cppimport
  18. .. _cmake:
  19. Building with CMake
  20. ===================
  21. For C++ codebases that have an existing CMake-based build system, a Python
  22. extension module can be created with just a few lines of code:
  23. .. code-block:: cmake
  24. cmake_minimum_required(VERSION 2.8.12)
  25. project(example)
  26. add_subdirectory(pybind11)
  27. pybind11_add_module(example example.cpp)
  28. This assumes that the pybind11 repository is located in a subdirectory named
  29. :file:`pybind11` and that the code is located in a file named :file:`example.cpp`.
  30. The CMake command ``add_subdirectory`` will import the pybind11 project which
  31. provides the ``pybind11_add_module`` function. It will take care of all the
  32. details needed to build a Python extension module on any platform.
  33. A working sample project, including a way to invoke CMake from :file:`setup.py` for
  34. PyPI integration, can be found in the [cmake_example]_ repository.
  35. .. [cmake_example] https://github.com/pybind/cmake_example
  36. pybind11_add_module
  37. -------------------
  38. To ease the creation of Python extension modules, pybind11 provides a CMake
  39. function with the following signature:
  40. .. code-block:: cmake
  41. pybind11_add_module(<name> [MODULE | SHARED] [EXCLUDE_FROM_ALL]
  42. [NO_EXTRAS] [THIN_LTO] source1 [source2 ...])
  43. This function behaves very much like CMake's builtin ``add_library`` (in fact,
  44. it's a wrapper function around that command). It will add a library target
  45. called ``<name>`` to be built from the listed source files. In addition, it
  46. will take care of all the Python-specific compiler and linker flags as well
  47. as the OS- and Python-version-specific file extension. The produced target
  48. ``<name>`` can be further manipulated with regular CMake commands.
  49. ``MODULE`` or ``SHARED`` may be given to specify the type of library. If no
  50. type is given, ``MODULE`` is used by default which ensures the creation of a
  51. Python-exclusive module. Specifying ``SHARED`` will create a more traditional
  52. dynamic library which can also be linked from elsewhere. ``EXCLUDE_FROM_ALL``
  53. removes this target from the default build (see CMake docs for details).
  54. Since pybind11 is a template library, ``pybind11_add_module`` adds compiler
  55. flags to ensure high quality code generation without bloat arising from long
  56. symbol names and duplication of code in different translation units. It
  57. sets default visibility to *hidden*, which is required for some pybind11
  58. features and functionality when attempting to load multiple pybind11 modules
  59. compiled under different pybind11 versions. It also adds additional flags
  60. enabling LTO (Link Time Optimization) and strip unneeded symbols. See the
  61. :ref:`FAQ entry <faq:symhidden>` for a more detailed explanation. These
  62. latter optimizations are never applied in ``Debug`` mode. If ``NO_EXTRAS`` is
  63. given, they will always be disabled, even in ``Release`` mode. However, this
  64. will result in code bloat and is generally not recommended.
  65. As stated above, LTO is enabled by default. Some newer compilers also support
  66. different flavors of LTO such as `ThinLTO`_. Setting ``THIN_LTO`` will cause
  67. the function to prefer this flavor if available. The function falls back to
  68. regular LTO if ``-flto=thin`` is not available.
  69. .. _ThinLTO: http://clang.llvm.org/docs/ThinLTO.html
  70. Configuration variables
  71. -----------------------
  72. By default, pybind11 will compile modules with the C++14 standard, if available
  73. on the target compiler, falling back to C++11 if C++14 support is not
  74. available. Note, however, that this default is subject to change: future
  75. pybind11 releases are expected to migrate to newer C++ standards as they become
  76. available. To override this, the standard flag can be given explicitly in
  77. ``PYBIND11_CPP_STANDARD``:
  78. .. code-block:: cmake
  79. # Use just one of these:
  80. # GCC/clang:
  81. set(PYBIND11_CPP_STANDARD -std=c++11)
  82. set(PYBIND11_CPP_STANDARD -std=c++14)
  83. set(PYBIND11_CPP_STANDARD -std=c++1z) # Experimental C++17 support
  84. # MSVC:
  85. set(PYBIND11_CPP_STANDARD /std:c++14)
  86. set(PYBIND11_CPP_STANDARD /std:c++latest) # Enables some MSVC C++17 features
  87. add_subdirectory(pybind11) # or find_package(pybind11)
  88. Note that this and all other configuration variables must be set **before** the
  89. call to ``add_subdirectory`` or ``find_package``. The variables can also be set
  90. when calling CMake from the command line using the ``-D<variable>=<value>`` flag.
  91. The target Python version can be selected by setting ``PYBIND11_PYTHON_VERSION``
  92. or an exact Python installation can be specified with ``PYTHON_EXECUTABLE``.
  93. For example:
  94. .. code-block:: bash
  95. cmake -DPYBIND11_PYTHON_VERSION=3.6 ..
  96. # or
  97. cmake -DPYTHON_EXECUTABLE=path/to/python ..
  98. find_package vs. add_subdirectory
  99. ---------------------------------
  100. For CMake-based projects that don't include the pybind11 repository internally,
  101. an external installation can be detected through ``find_package(pybind11)``.
  102. See the `Config file`_ docstring for details of relevant CMake variables.
  103. .. code-block:: cmake
  104. cmake_minimum_required(VERSION 2.8.12)
  105. project(example)
  106. find_package(pybind11 REQUIRED)
  107. pybind11_add_module(example example.cpp)
  108. Once detected, the aforementioned ``pybind11_add_module`` can be employed as
  109. before. The function usage and configuration variables are identical no matter
  110. if pybind11 is added as a subdirectory or found as an installed package. You
  111. can refer to the same [cmake_example]_ repository for a full sample project
  112. -- just swap out ``add_subdirectory`` for ``find_package``.
  113. .. _Config file: https://github.com/pybind/pybind11/blob/master/tools/pybind11Config.cmake.in
  114. Advanced: interface library target
  115. ----------------------------------
  116. When using a version of CMake greater than 3.0, pybind11 can additionally
  117. be used as a special *interface library* . The target ``pybind11::module``
  118. is available with pybind11 headers, Python headers and libraries as needed,
  119. and C++ compile definitions attached. This target is suitable for linking
  120. to an independently constructed (through ``add_library``, not
  121. ``pybind11_add_module``) target in the consuming project.
  122. .. code-block:: cmake
  123. cmake_minimum_required(VERSION 3.0)
  124. project(example)
  125. find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11)
  126. add_library(example MODULE main.cpp)
  127. target_link_libraries(example PRIVATE pybind11::module)
  128. set_target_properties(example PROPERTIES PREFIX "${PYTHON_MODULE_PREFIX}"
  129. SUFFIX "${PYTHON_MODULE_EXTENSION}")
  130. .. warning::
  131. Since pybind11 is a metatemplate library, it is crucial that certain
  132. compiler flags are provided to ensure high quality code generation. In
  133. contrast to the ``pybind11_add_module()`` command, the CMake interface
  134. library only provides the *minimal* set of parameters to ensure that the
  135. code using pybind11 compiles, but it does **not** pass these extra compiler
  136. flags (i.e. this is up to you).
  137. These include Link Time Optimization (``-flto`` on GCC/Clang/ICPC, ``/GL``
  138. and ``/LTCG`` on Visual Studio) and .OBJ files with many sections on Visual
  139. Studio (``/bigobj``). The :ref:`FAQ <faq:symhidden>` contains an
  140. explanation on why these are needed.
  141. Embedding the Python interpreter
  142. --------------------------------
  143. In addition to extension modules, pybind11 also supports embedding Python into
  144. a C++ executable or library. In CMake, simply link with the ``pybind11::embed``
  145. target. It provides everything needed to get the interpreter running. The Python
  146. headers and libraries are attached to the target. Unlike ``pybind11::module``,
  147. there is no need to manually set any additional properties here. For more
  148. information about usage in C++, see :doc:`/advanced/embedding`.
  149. .. code-block:: cmake
  150. cmake_minimum_required(VERSION 3.0)
  151. project(example)
  152. find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11)
  153. add_executable(example main.cpp)
  154. target_link_libraries(example PRIVATE pybind11::embed)
  155. .. _building_manually:
  156. Building manually
  157. =================
  158. pybind11 is a header-only library, hence it is not necessary to link against
  159. any special libraries and there are no intermediate (magic) translation steps.
  160. On Linux, you can compile an example such as the one given in
  161. :ref:`simple_example` using the following command:
  162. .. code-block:: bash
  163. $ c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`
  164. The flags given here assume that you're using Python 3. For Python 2, just
  165. change the executable appropriately (to ``python`` or ``python2``).
  166. The ``python3 -m pybind11 --includes`` command fetches the include paths for
  167. both pybind11 and Python headers. This assumes that pybind11 has been installed
  168. using ``pip`` or ``conda``. If it hasn't, you can also manually specify
  169. ``-I <path-to-pybind11>/include`` together with the Python includes path
  170. ``python3-config --includes``.
  171. Note that Python 2.7 modules don't use a special suffix, so you should simply
  172. use ``example.so`` instead of ``example`python3-config --extension-suffix```.
  173. Besides, the ``--extension-suffix`` option may or may not be available, depending
  174. on the distribution; in the latter case, the module extension can be manually
  175. set to ``.so``.
  176. On Mac OS: the build command is almost the same but it also requires passing
  177. the ``-undefined dynamic_lookup`` flag so as to ignore missing symbols when
  178. building the module:
  179. .. code-block:: bash
  180. $ c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`
  181. In general, it is advisable to include several additional build parameters
  182. that can considerably reduce the size of the created binary. Refer to section
  183. :ref:`cmake` for a detailed example of a suitable cross-platform CMake-based
  184. build system that works on all platforms including Windows.
  185. .. note::
  186. On Linux and macOS, it's better to (intentionally) not link against
  187. ``libpython``. The symbols will be resolved when the extension library
  188. is loaded into a Python binary. This is preferable because you might
  189. have several different installations of a given Python version (e.g. the
  190. system-provided Python, and one that ships with a piece of commercial
  191. software). In this way, the plugin will work with both versions, instead
  192. of possibly importing a second Python library into a process that already
  193. contains one (which will lead to a segfault).
  194. Generating binding code automatically
  195. =====================================
  196. The ``Binder`` project is a tool for automatic generation of pybind11 binding
  197. code by introspecting existing C++ codebases using LLVM/Clang. See the
  198. [binder]_ documentation for details.
  199. .. [binder] http://cppbinder.readthedocs.io/en/latest/about.html