compiling.rst 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. .. _compiling:
  2. Build systems
  3. #############
  4. .. _build-setuptools:
  5. Building with setuptools
  6. ========================
  7. For projects on PyPI, building with setuptools is the way to go. Sylvain Corlay
  8. has kindly provided an example project which shows how to set up everything,
  9. including automatic generation of documentation using Sphinx. Please refer to
  10. the [python_example]_ repository.
  11. .. [python_example] https://github.com/pybind/python_example
  12. A helper file is provided with pybind11 that can simplify usage with setuptools.
  13. To use pybind11 inside your ``setup.py``, you have to have some system to
  14. ensure that ``pybind11`` is installed when you build your package. There are
  15. four possible ways to do this, and pybind11 supports all four: You can ask all
  16. users to install pybind11 beforehand (bad), you can use
  17. :ref:`setup_helpers-pep518` (good, but very new and requires Pip 10),
  18. :ref:`setup_helpers-setup_requires` (discouraged by Python packagers now that
  19. PEP 518 is available, but it still works everywhere), or you can
  20. :ref:`setup_helpers-copy-manually` (always works but you have to manually sync
  21. your copy to get updates).
  22. An example of a ``setup.py`` using pybind11's helpers:
  23. .. code-block:: python
  24. from glob import glob
  25. from setuptools import setup
  26. from pybind11.setup_helpers import Pybind11Extension
  27. ext_modules = [
  28. Pybind11Extension(
  29. "python_example",
  30. sorted(glob("src/*.cpp")), # Sort source files for reproducibility
  31. ),
  32. ]
  33. setup(
  34. ...,
  35. ext_modules=ext_modules
  36. )
  37. If you want to do an automatic search for the highest supported C++ standard,
  38. that is supported via a ``build_ext`` command override; it will only affect
  39. ``Pybind11Extensions``:
  40. .. code-block:: python
  41. from glob import glob
  42. from setuptools import setup
  43. from pybind11.setup_helpers import Pybind11Extension, build_ext
  44. ext_modules = [
  45. Pybind11Extension(
  46. "python_example",
  47. sorted(glob("src/*.cpp")),
  48. ),
  49. ]
  50. setup(
  51. ...,
  52. cmdclass={"build_ext": build_ext},
  53. ext_modules=ext_modules
  54. )
  55. Since pybind11 does not require NumPy when building, a light-weight replacement
  56. for NumPy's parallel compilation distutils tool is included. Use it like this:
  57. .. code-block:: python
  58. from pybind11.setup_helpers import ParallelCompile
  59. # Optional multithreaded build
  60. ParallelCompile("NPY_NUM_BUILD_JOBS").install()
  61. setup(...)
  62. The argument is the name of an environment variable to control the number of
  63. threads, such as ``NPY_NUM_BUILD_JOBS`` (as used by NumPy), though you can set
  64. something different if you want; ``CMAKE_BUILD_PARALLEL_LEVEL`` is another choice
  65. a user might expect. You can also pass ``default=N`` to set the default number
  66. of threads (0 will take the number of threads available) and ``max=N``, the
  67. maximum number of threads; if you have a large extension you may want set this
  68. to a memory dependent number.
  69. If you are developing rapidly and have a lot of C++ files, you may want to
  70. avoid rebuilding files that have not changed. For simple cases were you are
  71. using ``pip install -e .`` and do not have local headers, you can skip the
  72. rebuild if a object file is newer than it's source (headers are not checked!)
  73. with the following:
  74. .. code-block:: python
  75. from pybind11.setup_helpers import ParallelCompile, naive_recompile
  76. SmartCompile("NPY_NUM_BUILD_JOBS", needs_recompile=naive_recompile).install()
  77. If you have a more complex build, you can implement a smarter function and pass
  78. it to ``needs_recompile``, or you can use [Ccache]_ instead. ``CXX="cache g++"
  79. pip install -e .`` would be the way to use it with GCC, for example. Unlike the
  80. simple solution, this even works even when not compiling in editable mode, but
  81. it does require Ccache to be installed.
  82. Keep in mind that Pip will not even attempt to rebuild if it thinks it has
  83. already built a copy of your code, which it deduces from the version number.
  84. One way to avoid this is to use [setuptools_scm]_, which will generate a
  85. version number that includes the number of commits since your last tag and a
  86. hash for a dirty directory. Another way to force a rebuild is purge your cache
  87. or use Pip's ``--no-cache-dir`` option.
  88. .. [Ccache] https://ccache.dev
  89. .. [setuptools_scm] https://github.com/pypa/setuptools_scm
  90. .. _setup_helpers-pep518:
  91. PEP 518 requirements (Pip 10+ required)
  92. ---------------------------------------
  93. If you use `PEP 518's <https://www.python.org/dev/peps/pep-0518/>`_
  94. ``pyproject.toml`` file, you can ensure that ``pybind11`` is available during
  95. the compilation of your project. When this file exists, Pip will make a new
  96. virtual environment, download just the packages listed here in ``requires=``,
  97. and build a wheel (binary Python package). It will then throw away the
  98. environment, and install your wheel.
  99. Your ``pyproject.toml`` file will likely look something like this:
  100. .. code-block:: toml
  101. [build-system]
  102. requires = ["setuptools>=42", "wheel", "pybind11~=2.6.1"]
  103. build-backend = "setuptools.build_meta"
  104. .. note::
  105. The main drawback to this method is that a `PEP 517`_ compliant build tool,
  106. such as Pip 10+, is required for this approach to work; older versions of
  107. Pip completely ignore this file. If you distribute binaries (called wheels
  108. in Python) using something like `cibuildwheel`_, remember that ``setup.py``
  109. and ``pyproject.toml`` are not even contained in the wheel, so this high
  110. Pip requirement is only for source builds, and will not affect users of
  111. your binary wheels. If you are building SDists and wheels, then
  112. `pypa-build`_ is the recommended offical tool.
  113. .. _PEP 517: https://www.python.org/dev/peps/pep-0517/
  114. .. _cibuildwheel: https://cibuildwheel.readthedocs.io
  115. .. _pypa-build: https://pypa-build.readthedocs.io/en/latest/
  116. .. _setup_helpers-setup_requires:
  117. Classic ``setup_requires``
  118. --------------------------
  119. If you want to support old versions of Pip with the classic
  120. ``setup_requires=["pybind11"]`` keyword argument to setup, which triggers a
  121. two-phase ``setup.py`` run, then you will need to use something like this to
  122. ensure the first pass works (which has not yet installed the ``setup_requires``
  123. packages, since it can't install something it does not know about):
  124. .. code-block:: python
  125. try:
  126. from pybind11.setup_helpers import Pybind11Extension
  127. except ImportError:
  128. from setuptools import Extension as Pybind11Extension
  129. It doesn't matter that the Extension class is not the enhanced subclass for the
  130. first pass run; and the second pass will have the ``setup_requires``
  131. requirements.
  132. This is obviously more of a hack than the PEP 518 method, but it supports
  133. ancient versions of Pip.
  134. .. _setup_helpers-copy-manually:
  135. Copy manually
  136. -------------
  137. You can also copy ``setup_helpers.py`` directly to your project; it was
  138. designed to be usable standalone, like the old example ``setup.py``. You can
  139. set ``include_pybind11=False`` to skip including the pybind11 package headers,
  140. so you can use it with git submodules and a specific git version. If you use
  141. this, you will need to import from a local file in ``setup.py`` and ensure the
  142. helper file is part of your MANIFEST.
  143. Closely related, if you include pybind11 as a subproject, you can run the
  144. ``setup_helpers.py`` inplace. If loaded correctly, this should even pick up
  145. the correct include for pybind11, though you can turn it off as shown above if
  146. you want to input it manually.
  147. Suggested usage if you have pybind11 as a submodule in ``extern/pybind11``:
  148. .. code-block:: python
  149. DIR = os.path.abspath(os.path.dirname(__file__))
  150. sys.path.append(os.path.join(DIR, "extern", "pybind11"))
  151. from pybind11.setup_helpers import Pybind11Extension # noqa: E402
  152. del sys.path[-1]
  153. .. versionchanged:: 2.6
  154. Added ``setup_helpers`` file.
  155. Building with cppimport
  156. ========================
  157. [cppimport]_ is a small Python import hook that determines whether there is a C++
  158. source file whose name matches the requested module. If there is, the file is
  159. compiled as a Python extension using pybind11 and placed in the same folder as
  160. the C++ source file. Python is then able to find the module and load it.
  161. .. [cppimport] https://github.com/tbenthompson/cppimport
  162. .. _cmake:
  163. Building with CMake
  164. ===================
  165. For C++ codebases that have an existing CMake-based build system, a Python
  166. extension module can be created with just a few lines of code:
  167. .. code-block:: cmake
  168. cmake_minimum_required(VERSION 3.4...3.18)
  169. project(example LANGUAGES CXX)
  170. add_subdirectory(pybind11)
  171. pybind11_add_module(example example.cpp)
  172. This assumes that the pybind11 repository is located in a subdirectory named
  173. :file:`pybind11` and that the code is located in a file named :file:`example.cpp`.
  174. The CMake command ``add_subdirectory`` will import the pybind11 project which
  175. provides the ``pybind11_add_module`` function. It will take care of all the
  176. details needed to build a Python extension module on any platform.
  177. A working sample project, including a way to invoke CMake from :file:`setup.py` for
  178. PyPI integration, can be found in the [cmake_example]_ repository.
  179. .. [cmake_example] https://github.com/pybind/cmake_example
  180. .. versionchanged:: 2.6
  181. CMake 3.4+ is required.
  182. Further information can be found at :doc:`cmake/index`.
  183. pybind11_add_module
  184. -------------------
  185. To ease the creation of Python extension modules, pybind11 provides a CMake
  186. function with the following signature:
  187. .. code-block:: cmake
  188. pybind11_add_module(<name> [MODULE | SHARED] [EXCLUDE_FROM_ALL]
  189. [NO_EXTRAS] [THIN_LTO] [OPT_SIZE] source1 [source2 ...])
  190. This function behaves very much like CMake's builtin ``add_library`` (in fact,
  191. it's a wrapper function around that command). It will add a library target
  192. called ``<name>`` to be built from the listed source files. In addition, it
  193. will take care of all the Python-specific compiler and linker flags as well
  194. as the OS- and Python-version-specific file extension. The produced target
  195. ``<name>`` can be further manipulated with regular CMake commands.
  196. ``MODULE`` or ``SHARED`` may be given to specify the type of library. If no
  197. type is given, ``MODULE`` is used by default which ensures the creation of a
  198. Python-exclusive module. Specifying ``SHARED`` will create a more traditional
  199. dynamic library which can also be linked from elsewhere. ``EXCLUDE_FROM_ALL``
  200. removes this target from the default build (see CMake docs for details).
  201. Since pybind11 is a template library, ``pybind11_add_module`` adds compiler
  202. flags to ensure high quality code generation without bloat arising from long
  203. symbol names and duplication of code in different translation units. It
  204. sets default visibility to *hidden*, which is required for some pybind11
  205. features and functionality when attempting to load multiple pybind11 modules
  206. compiled under different pybind11 versions. It also adds additional flags
  207. enabling LTO (Link Time Optimization) and strip unneeded symbols. See the
  208. :ref:`FAQ entry <faq:symhidden>` for a more detailed explanation. These
  209. latter optimizations are never applied in ``Debug`` mode. If ``NO_EXTRAS`` is
  210. given, they will always be disabled, even in ``Release`` mode. However, this
  211. will result in code bloat and is generally not recommended.
  212. As stated above, LTO is enabled by default. Some newer compilers also support
  213. different flavors of LTO such as `ThinLTO`_. Setting ``THIN_LTO`` will cause
  214. the function to prefer this flavor if available. The function falls back to
  215. regular LTO if ``-flto=thin`` is not available. If
  216. ``CMAKE_INTERPROCEDURAL_OPTIMIZATION`` is set (either ``ON`` or ``OFF``), then
  217. that will be respected instead of the built-in flag search.
  218. .. note::
  219. If you want to set the property form on targets or the
  220. ``CMAKE_INTERPROCEDURAL_OPTIMIZATION_<CONFIG>`` versions of this, you should
  221. still use ``set(CMAKE_INTERPROCEDURAL_OPTIMIZATION OFF)`` (otherwise a
  222. no-op) to disable pybind11's ipo flags.
  223. The ``OPT_SIZE`` flag enables size-based optimization equivalent to the
  224. standard ``/Os`` or ``-Os`` compiler flags and the ``MinSizeRel`` build type,
  225. which avoid optimizations that that can substantially increase the size of the
  226. resulting binary. This flag is particularly useful in projects that are split
  227. into performance-critical parts and associated bindings. In this case, we can
  228. compile the project in release mode (and hence, optimize performance globally),
  229. and specify ``OPT_SIZE`` for the binding target, where size might be the main
  230. concern as performance is often less critical here. A ~25% size reduction has
  231. been observed in practice. This flag only changes the optimization behavior at
  232. a per-target level and takes precedence over the global CMake build type
  233. (``Release``, ``RelWithDebInfo``) except for ``Debug`` builds, where
  234. optimizations remain disabled.
  235. .. _ThinLTO: http://clang.llvm.org/docs/ThinLTO.html
  236. Configuration variables
  237. -----------------------
  238. By default, pybind11 will compile modules with the compiler default or the
  239. minimum standard required by pybind11, whichever is higher. You can set the
  240. standard explicitly with
  241. `CMAKE_CXX_STANDARD <https://cmake.org/cmake/help/latest/variable/CMAKE_CXX_STANDARD.html>`_:
  242. .. code-block:: cmake
  243. set(CMAKE_CXX_STANDARD 14 CACHE STRING "C++ version selection") # or 11, 14, 17, 20
  244. set(CMAKE_CXX_STANDARD_REQUIRED ON) # optional, ensure standard is supported
  245. set(CMAKE_CXX_EXTENSIONS OFF) # optional, keep compiler extensionsn off
  246. The variables can also be set when calling CMake from the command line using
  247. the ``-D<variable>=<value>`` flag. You can also manually set ``CXX_STANDARD``
  248. on a target or use ``target_compile_features`` on your targets - anything that
  249. CMake supports.
  250. Classic Python support: The target Python version can be selected by setting
  251. ``PYBIND11_PYTHON_VERSION`` or an exact Python installation can be specified
  252. with ``PYTHON_EXECUTABLE``. For example:
  253. .. code-block:: bash
  254. cmake -DPYBIND11_PYTHON_VERSION=3.6 ..
  255. # Another method:
  256. cmake -DPYTHON_EXECUTABLE=/path/to/python ..
  257. # This often is a good way to get the current Python, works in environments:
  258. cmake -DPYTHON_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)") ..
  259. find_package vs. add_subdirectory
  260. ---------------------------------
  261. For CMake-based projects that don't include the pybind11 repository internally,
  262. an external installation can be detected through ``find_package(pybind11)``.
  263. See the `Config file`_ docstring for details of relevant CMake variables.
  264. .. code-block:: cmake
  265. cmake_minimum_required(VERSION 3.4...3.18)
  266. project(example LANGUAGES CXX)
  267. find_package(pybind11 REQUIRED)
  268. pybind11_add_module(example example.cpp)
  269. Note that ``find_package(pybind11)`` will only work correctly if pybind11
  270. has been correctly installed on the system, e. g. after downloading or cloning
  271. the pybind11 repository :
  272. .. code-block:: bash
  273. # Classic CMake
  274. cd pybind11
  275. mkdir build
  276. cd build
  277. cmake ..
  278. make install
  279. # CMake 3.15+
  280. cd pybind11
  281. cmake -S . -B build
  282. cmake --build build -j 2 # Build on 2 cores
  283. cmake --install build
  284. Once detected, the aforementioned ``pybind11_add_module`` can be employed as
  285. before. The function usage and configuration variables are identical no matter
  286. if pybind11 is added as a subdirectory or found as an installed package. You
  287. can refer to the same [cmake_example]_ repository for a full sample project
  288. -- just swap out ``add_subdirectory`` for ``find_package``.
  289. .. _Config file: https://github.com/pybind/pybind11/blob/master/tools/pybind11Config.cmake.in
  290. .. _find-python-mode:
  291. FindPython mode
  292. ---------------
  293. CMake 3.12+ (3.15+ recommended, 3.18.2+ ideal) added a new module called
  294. FindPython that had a highly improved search algorithm and modern targets
  295. and tools. If you use FindPython, pybind11 will detect this and use the
  296. existing targets instead:
  297. .. code-block:: cmake
  298. cmake_minumum_required(VERSION 3.15...3.19)
  299. project(example LANGUAGES CXX)
  300. find_package(Python COMPONENTS Interpreter Development REQUIRED)
  301. find_package(pybind11 CONFIG REQUIRED)
  302. # or add_subdirectory(pybind11)
  303. pybind11_add_module(example example.cpp)
  304. You can also use the targets (as listed below) with FindPython. If you define
  305. ``PYBIND11_FINDPYTHON``, pybind11 will perform the FindPython step for you
  306. (mostly useful when building pybind11's own tests, or as a way to change search
  307. algorithms from the CMake invocation, with ``-DPYBIND11_FINDPYTHON=ON``.
  308. .. warning::
  309. If you use FindPython2 and FindPython3 to dual-target Python, use the
  310. individual targets listed below, and avoid targets that directly include
  311. Python parts.
  312. There are `many ways to hint or force a discovery of a specific Python
  313. installation <https://cmake.org/cmake/help/latest/module/FindPython.html>`_),
  314. setting ``Python_ROOT_DIR`` may be the most common one (though with
  315. virtualenv/venv support, and Conda support, this tends to find the correct
  316. Python version more often than the old system did).
  317. .. warning::
  318. When the Python libraries (i.e. ``libpythonXX.a`` and ``libpythonXX.so``
  319. on Unix) are not available, as is the case on a manylinux image, the
  320. ``Development`` component will not be resolved by ``FindPython``. When not
  321. using the embedding functionality, CMake 3.18+ allows you to specify
  322. ``Development.Module`` instead of ``Development`` to resolve this issue.
  323. .. versionadded:: 2.6
  324. Advanced: interface library targets
  325. -----------------------------------
  326. Pybind11 supports modern CMake usage patterns with a set of interface targets,
  327. available in all modes. The targets provided are:
  328. ``pybind11::headers``
  329. Just the pybind11 headers and minimum compile requirements
  330. ``pybind11::python2_no_register``
  331. Quiets the warning/error when mixing C++14 or higher and Python 2
  332. ``pybind11::pybind11``
  333. Python headers + ``pybind11::headers`` + ``pybind11::python2_no_register`` (Python 2 only)
  334. ``pybind11::python_link_helper``
  335. Just the "linking" part of pybind11:module
  336. ``pybind11::module``
  337. Everything for extension modules - ``pybind11::pybind11`` + ``Python::Module`` (FindPython CMake 3.15+) or ``pybind11::python_link_helper``
  338. ``pybind11::embed``
  339. Everything for embedding the Python interpreter - ``pybind11::pybind11`` + ``Python::Embed`` (FindPython) or Python libs
  340. ``pybind11::lto`` / ``pybind11::thin_lto``
  341. An alternative to `INTERPROCEDURAL_OPTIMIZATION` for adding link-time optimization.
  342. ``pybind11::windows_extras``
  343. ``/bigobj`` and ``/mp`` for MSVC.
  344. ``pybind11::opt_size``
  345. ``/Os`` for MSVC, ``-Os`` for other compilers. Does nothing for debug builds.
  346. Two helper functions are also provided:
  347. ``pybind11_strip(target)``
  348. Strips a target (uses ``CMAKE_STRIP`` after the target is built)
  349. ``pybind11_extension(target)``
  350. Sets the correct extension (with SOABI) for a target.
  351. You can use these targets to build complex applications. For example, the
  352. ``add_python_module`` function is identical to:
  353. .. code-block:: cmake
  354. cmake_minimum_required(VERSION 3.4)
  355. project(example LANGUAGES CXX)
  356. find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11)
  357. add_library(example MODULE main.cpp)
  358. target_link_libraries(example PRIVATE pybind11::module pybind11::lto pybind11::windows_extras)
  359. pybind11_extension(example)
  360. pybind11_strip(example)
  361. set_target_properties(example PROPERTIES CXX_VISIBILITY_PRESET "hidden"
  362. CUDA_VISIBILITY_PRESET "hidden")
  363. Instead of setting properties, you can set ``CMAKE_*`` variables to initialize these correctly.
  364. .. warning::
  365. Since pybind11 is a metatemplate library, it is crucial that certain
  366. compiler flags are provided to ensure high quality code generation. In
  367. contrast to the ``pybind11_add_module()`` command, the CMake interface
  368. provides a *composable* set of targets to ensure that you retain flexibility.
  369. It can be expecially important to provide or set these properties; the
  370. :ref:`FAQ <faq:symhidden>` contains an explanation on why these are needed.
  371. .. versionadded:: 2.6
  372. .. _nopython-mode:
  373. Advanced: NOPYTHON mode
  374. -----------------------
  375. If you want complete control, you can set ``PYBIND11_NOPYTHON`` to completely
  376. disable Python integration (this also happens if you run ``FindPython2`` and
  377. ``FindPython3`` without running ``FindPython``). This gives you complete
  378. freedom to integrate into an existing system (like `Scikit-Build's
  379. <https://scikit-build.readthedocs.io>`_ ``PythonExtensions``).
  380. ``pybind11_add_module`` and ``pybind11_extension`` will be unavailable, and the
  381. targets will be missing any Python specific behavior.
  382. .. versionadded:: 2.6
  383. Embedding the Python interpreter
  384. --------------------------------
  385. In addition to extension modules, pybind11 also supports embedding Python into
  386. a C++ executable or library. In CMake, simply link with the ``pybind11::embed``
  387. target. It provides everything needed to get the interpreter running. The Python
  388. headers and libraries are attached to the target. Unlike ``pybind11::module``,
  389. there is no need to manually set any additional properties here. For more
  390. information about usage in C++, see :doc:`/advanced/embedding`.
  391. .. code-block:: cmake
  392. cmake_minimum_required(VERSION 3.4...3.18)
  393. project(example LANGUAGES CXX)
  394. find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11)
  395. add_executable(example main.cpp)
  396. target_link_libraries(example PRIVATE pybind11::embed)
  397. .. _building_manually:
  398. Building manually
  399. =================
  400. pybind11 is a header-only library, hence it is not necessary to link against
  401. any special libraries and there are no intermediate (magic) translation steps.
  402. On Linux, you can compile an example such as the one given in
  403. :ref:`simple_example` using the following command:
  404. .. code-block:: bash
  405. $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
  406. The flags given here assume that you're using Python 3. For Python 2, just
  407. change the executable appropriately (to ``python`` or ``python2``).
  408. The ``python3 -m pybind11 --includes`` command fetches the include paths for
  409. both pybind11 and Python headers. This assumes that pybind11 has been installed
  410. using ``pip`` or ``conda``. If it hasn't, you can also manually specify
  411. ``-I <path-to-pybind11>/include`` together with the Python includes path
  412. ``python3-config --includes``.
  413. Note that Python 2.7 modules don't use a special suffix, so you should simply
  414. use ``example.so`` instead of ``example$(python3-config --extension-suffix)``.
  415. Besides, the ``--extension-suffix`` option may or may not be available, depending
  416. on the distribution; in the latter case, the module extension can be manually
  417. set to ``.so``.
  418. On macOS: the build command is almost the same but it also requires passing
  419. the ``-undefined dynamic_lookup`` flag so as to ignore missing symbols when
  420. building the module:
  421. .. code-block:: bash
  422. $ c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
  423. In general, it is advisable to include several additional build parameters
  424. that can considerably reduce the size of the created binary. Refer to section
  425. :ref:`cmake` for a detailed example of a suitable cross-platform CMake-based
  426. build system that works on all platforms including Windows.
  427. .. note::
  428. On Linux and macOS, it's better to (intentionally) not link against
  429. ``libpython``. The symbols will be resolved when the extension library
  430. is loaded into a Python binary. This is preferable because you might
  431. have several different installations of a given Python version (e.g. the
  432. system-provided Python, and one that ships with a piece of commercial
  433. software). In this way, the plugin will work with both versions, instead
  434. of possibly importing a second Python library into a process that already
  435. contains one (which will lead to a segfault).
  436. Building with Bazel
  437. ===================
  438. You can build with the Bazel build system using the `pybind11_bazel
  439. <https://github.com/pybind/pybind11_bazel>`_ repository.
  440. Generating binding code automatically
  441. =====================================
  442. The ``Binder`` project is a tool for automatic generation of pybind11 binding
  443. code by introspecting existing C++ codebases using LLVM/Clang. See the
  444. [binder]_ documentation for details.
  445. .. [binder] http://cppbinder.readthedocs.io/en/latest/about.html
  446. [AutoWIG]_ is a Python library that wraps automatically compiled libraries into
  447. high-level languages. It parses C++ code using LLVM/Clang technologies and
  448. generates the wrappers using the Mako templating engine. The approach is automatic,
  449. extensible, and applies to very complex C++ libraries, composed of thousands of
  450. classes or incorporating modern meta-programming constructs.
  451. .. [AutoWIG] https://github.com/StatisKit/AutoWIG
  452. [robotpy-build]_ is a is a pure python, cross platform build tool that aims to
  453. simplify creation of python wheels for pybind11 projects, and provide
  454. cross-project dependency management. Additionally, it is able to autogenerate
  455. customizable pybind11-based wrappers by parsing C++ header files.
  456. .. [robotpy-build] https://robotpy-build.readthedocs.io