blob: 39cde8c528a01f493b1ee7b2a534d28a8e03deb0 [file] [log] [blame]
Ivan Smirnov5cbfda52017-08-30 20:58:43 +01001.. _compiling:
2
Wenzel Jakob4a48afb2016-03-09 21:31:21 +01003Build systems
4#############
5
Henry Schreinerfd61f502020-09-16 17:13:41 -04006.. _build-setuptools:
7
Wenzel Jakob4a48afb2016-03-09 21:31:21 +01008Building with setuptools
9========================
10
11For projects on PyPI, building with setuptools is the way to go. Sylvain Corlay
12has kindly provided an example project which shows how to set up everything,
13including automatic generation of documentation using Sphinx. Please refer to
Wenzel Jakobca8dc082016-06-03 14:24:17 +020014the [python_example]_ repository.
Wenzel Jakob4a48afb2016-03-09 21:31:21 +010015
Wenzel Jakobca8dc082016-06-03 14:24:17 +020016.. [python_example] https://github.com/pybind/python_example
Wenzel Jakob4a48afb2016-03-09 21:31:21 +010017
Henry Schreinerfd61f502020-09-16 17:13:41 -040018A helper file is provided with pybind11 that can simplify usage with setuptools.
19
20To use pybind11 inside your ``setup.py``, you have to have some system to
21ensure that ``pybind11`` is installed when you build your package. There are
22four possible ways to do this, and pybind11 supports all four: You can ask all
23users to install pybind11 beforehand (bad), you can use
24:ref:`setup_helpers-pep518` (good, but very new and requires Pip 10),
25:ref:`setup_helpers-setup_requires` (discouraged by Python packagers now that
26PEP 518 is available, but it still works everywhere), or you can
27:ref:`setup_helpers-copy-manually` (always works but you have to manually sync
28your copy to get updates).
29
30An example of a ``setup.py`` using pybind11's helpers:
31
32.. code-block:: python
33
34 from setuptools import setup
35 from pybind11.setup_helpers import Pybind11Extension
36
37 ext_modules = [
38 Pybind11Extension(
39 "python_example",
40 ["src/main.cpp"],
41 ),
42 ]
43
44 setup(
45 ...,
46 ext_modules=ext_modules
47 )
48
49If you want to do an automatic search for the highest supported C++ standard,
50that is supported via a ``build_ext`` command override; it will only affect
51``Pybind11Extensions``:
52
53.. code-block:: python
54
55 from setuptools import setup
56 from pybind11.setup_helpers import Pybind11Extension, build_ext
57
58 ext_modules = [
59 Pybind11Extension(
60 "python_example",
61 ["src/main.cpp"],
62 ),
63 ]
64
65 setup(
66 ...,
67 cmdclass={"build_ext": build_ext},
68 ext_modules=ext_modules
69 )
70
Henry Schreinerb9d00272020-10-02 10:03:35 -040071Since pybind11 does not require NumPy when building, a light-weight replacement
72for NumPy's parallel compilation distutils tool is included. Use it like this:
73
74 from pybind11.setup_helpers import ParallelCompile
75
76 # Optional multithreaded build
77 ParallelCompile("NPY_NUM_BUILD_JOBS").install()
78
79 setup(...
80
81The argument is the name of an environment variable to control the number of
82threads, such as ``NPY_NUM_BUILD_JOBS`` (as used by NumPy), though you can set
83something different if you want. You can also pass ``default=N`` to set the
84default number of threads (0 will take the number of threads available) and
85``max=N``, the maximum number of threads; if you have a large extension you may
86want set this to a memory dependent number.
87
Henry Schreinerfd61f502020-09-16 17:13:41 -040088.. _setup_helpers-pep518:
89
90PEP 518 requirements (Pip 10+ required)
91---------------------------------------
92
93If 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
95the compilation of your project. When this file exists, Pip will make a new
96virtual environment, download just the packages listed here in ``requires=``,
97and build a wheel (binary Python package). It will then throw away the
98environment, and install your wheel.
99
100Your ``pyproject.toml`` file will likely look something like this:
101
102.. code-block:: toml
103
104 [build-system]
105 requires = ["setuptools", "wheel", "pybind11==2.6.0"]
106 build-backend = "setuptools.build_meta"
107
108.. note::
109
110 The main drawback to this method is that a `PEP 517`_ compliant build tool,
111 such as Pip 10+, is required for this approach to work; older versions of
112 Pip completely ignore this file. If you distribute binaries (called wheels
113 in Python) using something like `cibuildwheel`_, remember that ``setup.py``
114 and ``pyproject.toml`` are not even contained in the wheel, so this high
115 Pip requirement is only for source builds, and will not affect users of
116 your binary wheels.
117
118.. _PEP 517: https://www.python.org/dev/peps/pep-0517/
119.. _cibuildwheel: https://cibuildwheel.readthedocs.io
120
121.. _setup_helpers-setup_requires:
122
123Classic ``setup_requires``
124--------------------------
125
126If you want to support old versions of Pip with the classic
127``setup_requires=["pybind11"]`` keyword argument to setup, which triggers a
128two-phase ``setup.py`` run, then you will need to use something like this to
129ensure the first pass works (which has not yet installed the ``setup_requires``
130packages, since it can't install something it does not know about):
131
132.. code-block:: python
133
134 try:
135 from pybind11.setup_helpers import Pybind11Extension
136 except ImportError:
137 from setuptools import Extension as Pybind11Extension
138
139
140It doesn't matter that the Extension class is not the enhanced subclass for the
141first pass run; and the second pass will have the ``setup_requires``
142requirements.
143
144This is obviously more of a hack than the PEP 518 method, but it supports
145ancient versions of Pip.
146
147.. _setup_helpers-copy-manually:
148
149Copy manually
150-------------
151
152You can also copy ``setup_helpers.py`` directly to your project; it was
153designed to be usable standalone, like the old example ``setup.py``. You can
154set ``include_pybind11=False`` to skip including the pybind11 package headers,
155so you can use it with git submodules and a specific git version. If you use
156this, you will need to import from a local file in ``setup.py`` and ensure the
157helper file is part of your MANIFEST.
158
159
160.. versionchanged:: 2.6
161
162 Added ``setup_helpers`` file.
163
Wenzel Jakoba439cca2016-05-17 10:47:52 +0200164Building with cppimport
165========================
166
Dean Moldovan8665ee82017-08-17 15:01:43 +0200167[cppimport]_ is a small Python import hook that determines whether there is a C++
168source file whose name matches the requested module. If there is, the file is
169compiled as a Python extension using pybind11 and placed in the same folder as
170the C++ source file. Python is then able to find the module and load it.
Wenzel Jakoba439cca2016-05-17 10:47:52 +0200171
172.. [cppimport] https://github.com/tbenthompson/cppimport
173
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200174.. _cmake:
175
176Building with CMake
177===================
178
Wenzel Jakobfe342412016-09-06 13:02:29 +0900179For C++ codebases that have an existing CMake-based build system, a Python
Dean Moldovan24ddf4b2016-05-27 00:11:52 +0200180extension module can be created with just a few lines of code:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200181
182.. code-block:: cmake
183
Henry Schreiner1729aae2020-08-19 12:26:26 -0400184 cmake_minimum_required(VERSION 3.4...3.18)
185 project(example LANGUAGES CXX)
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200186
Dean Moldovan24ddf4b2016-05-27 00:11:52 +0200187 add_subdirectory(pybind11)
188 pybind11_add_module(example example.cpp)
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200189
Wenzel Jakobfe342412016-09-06 13:02:29 +0900190This assumes that the pybind11 repository is located in a subdirectory named
Dean Moldovan24ddf4b2016-05-27 00:11:52 +0200191:file:`pybind11` and that the code is located in a file named :file:`example.cpp`.
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100192The CMake command ``add_subdirectory`` will import the pybind11 project which
193provides the ``pybind11_add_module`` function. It will take care of all the
194details needed to build a Python extension module on any platform.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200195
Dean Moldovan24ddf4b2016-05-27 00:11:52 +0200196A working sample project, including a way to invoke CMake from :file:`setup.py` for
197PyPI integration, can be found in the [cmake_example]_ repository.
Wenzel Jakobcaa9d442016-01-17 22:36:34 +0100198
Wenzel Jakobaa79af02016-06-03 12:23:24 +0200199.. [cmake_example] https://github.com/pybind/cmake_example
Lori A. Burns5cafc992016-12-13 10:55:38 -0500200
Henry Schreiner1729aae2020-08-19 12:26:26 -0400201.. versionchanged:: 2.6
202 CMake 3.4+ is required.
203
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100204pybind11_add_module
205-------------------
Lori A. Burns5cafc992016-12-13 10:55:38 -0500206
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100207To ease the creation of Python extension modules, pybind11 provides a CMake
208function with the following signature:
209
210.. code-block:: cmake
211
212 pybind11_add_module(<name> [MODULE | SHARED] [EXCLUDE_FROM_ALL]
Wenzel Jakob36c666f2020-09-04 23:31:05 +0200213 [NO_EXTRAS] [THIN_LTO] [OPT_SIZE] source1 [source2 ...])
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100214
215This function behaves very much like CMake's builtin ``add_library`` (in fact,
216it's a wrapper function around that command). It will add a library target
217called ``<name>`` to be built from the listed source files. In addition, it
218will take care of all the Python-specific compiler and linker flags as well
219as the OS- and Python-version-specific file extension. The produced target
220``<name>`` can be further manipulated with regular CMake commands.
221
222``MODULE`` or ``SHARED`` may be given to specify the type of library. If no
223type is given, ``MODULE`` is used by default which ensures the creation of a
224Python-exclusive module. Specifying ``SHARED`` will create a more traditional
225dynamic library which can also be linked from elsewhere. ``EXCLUDE_FROM_ALL``
226removes this target from the default build (see CMake docs for details).
227
228Since pybind11 is a template library, ``pybind11_add_module`` adds compiler
229flags to ensure high quality code generation without bloat arising from long
Jason Rhinelander97aa54f2017-08-10 12:08:42 -0400230symbol names and duplication of code in different translation units. It
231sets default visibility to *hidden*, which is required for some pybind11
232features and functionality when attempting to load multiple pybind11 modules
233compiled under different pybind11 versions. It also adds additional flags
234enabling LTO (Link Time Optimization) and strip unneeded symbols. See the
235:ref:`FAQ entry <faq:symhidden>` for a more detailed explanation. These
236latter optimizations are never applied in ``Debug`` mode. If ``NO_EXTRAS`` is
237given, they will always be disabled, even in ``Release`` mode. However, this
238will result in code bloat and is generally not recommended.
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100239
240As stated above, LTO is enabled by default. Some newer compilers also support
241different flavors of LTO such as `ThinLTO`_. Setting ``THIN_LTO`` will cause
242the function to prefer this flavor if available. The function falls back to
Henry Schreiner1729aae2020-08-19 12:26:26 -0400243regular LTO if ``-flto=thin`` is not available. If
244``CMAKE_INTERPROCEDURAL_OPTIMIZATION`` is set (either ON or OFF), then that
245will be respected instead of the built-in flag search.
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100246
Wenzel Jakob36c666f2020-09-04 23:31:05 +0200247The ``OPT_SIZE`` flag enables size-based optimization equivalent to the
248standard ``/Os`` or ``-Os`` compiler flags and the ``MinSizeRel`` build type,
249which avoid optimizations that that can substantially increase the size of the
250resulting binary. This flag is particularly useful in projects that are split
251into performance-critical parts and associated bindings. In this case, we can
252compile the project in release mode (and hence, optimize performance globally),
253and specify ``OPT_SIZE`` for the binding target, where size might be the main
254concern as performance is often less critical here. A ~25% size reduction has
255been observed in practice. This flag only changes the optimization behavior at
256a per-target level and takes precedence over the global CMake build type
257(``Release``, ``RelWithDebInfo``) except for ``Debug`` builds, where
258optimizations remain disabled.
259
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100260.. _ThinLTO: http://clang.llvm.org/docs/ThinLTO.html
261
262Configuration variables
263-----------------------
264
Henry Schreiner6ec17752020-07-28 00:43:12 -0400265By default, pybind11 will compile modules with the compiler default or the
Henry Schreiner1651c322020-07-30 16:04:26 -0400266minimum standard required by pybind11, whichever is higher. You can set the
Henry Schreiner6ec17752020-07-28 00:43:12 -0400267standard explicitly with
268`CMAKE_CXX_STANDARD <https://cmake.org/cmake/help/latest/variable/CMAKE_CXX_STANDARD.html>`_:
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100269
270.. code-block:: cmake
271
Henry Schreiner1b92cd12020-07-29 15:02:53 -0400272 set(CMAKE_CXX_STANDARD 14) # or 11, 14, 17, 20
273 set(CMAKE_CXX_STANDARD_REQUIRED ON) # optional, ensure standard is supported
274 set(CMAKE_CXX_EXTENSIONS OFF) # optional, keep compiler extensionsn off
Jason Rhinelander77710ff2017-05-09 14:37:48 -0400275
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100276
Henry Schreiner6ec17752020-07-28 00:43:12 -0400277The variables can also be set when calling CMake from the command line using
278the ``-D<variable>=<value>`` flag. You can also manually set ``CXX_STANDARD``
279on a target or use ``target_compile_features`` on your targets - anything that
280CMake supports.
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100281
Henry Schreiner1729aae2020-08-19 12:26:26 -0400282Classic Python support: The target Python version can be selected by setting
283``PYBIND11_PYTHON_VERSION`` or an exact Python installation can be specified
284with ``PYTHON_EXECUTABLE``. For example:
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100285
286.. code-block:: bash
287
288 cmake -DPYBIND11_PYTHON_VERSION=3.6 ..
Henry Schreiner1b92cd12020-07-29 15:02:53 -0400289
290 # Another method:
291 cmake -DPYTHON_EXECUTABLE=/path/to/python ..
292
Henry Schreiner1651c322020-07-30 16:04:26 -0400293 # This often is a good way to get the current Python, works in environments:
Henry Schreiner6ec17752020-07-28 00:43:12 -0400294 cmake -DPYTHON_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)") ..
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100295
Henry Schreiner1729aae2020-08-19 12:26:26 -0400296
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100297find_package vs. add_subdirectory
298---------------------------------
299
300For CMake-based projects that don't include the pybind11 repository internally,
301an external installation can be detected through ``find_package(pybind11)``.
302See the `Config file`_ docstring for details of relevant CMake variables.
Lori A. Burns5cafc992016-12-13 10:55:38 -0500303
304.. code-block:: cmake
305
Henry Schreiner1729aae2020-08-19 12:26:26 -0400306 cmake_minimum_required(VERSION 3.4...3.18)
307 project(example LANGUAGES CXX)
Lori A. Burns5cafc992016-12-13 10:55:38 -0500308
309 find_package(pybind11 REQUIRED)
310 pybind11_add_module(example example.cpp)
311
nstelzenc2514342019-06-10 16:35:36 +0200312Note that ``find_package(pybind11)`` will only work correctly if pybind11
313has been correctly installed on the system, e. g. after downloading or cloning
314the pybind11 repository :
315
316.. code-block:: bash
317
Henry Schreiner1b92cd12020-07-29 15:02:53 -0400318 # Classic CMake
nstelzenc2514342019-06-10 16:35:36 +0200319 cd pybind11
320 mkdir build
321 cd build
322 cmake ..
323 make install
324
Henry Schreiner1b92cd12020-07-29 15:02:53 -0400325 # CMake 3.15+
326 cd pybind11
327 cmake -S . -B build
328 cmake --build build -j 2 # Build on 2 cores
329 cmake --install build
330
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100331Once detected, the aforementioned ``pybind11_add_module`` can be employed as
332before. The function usage and configuration variables are identical no matter
333if pybind11 is added as a subdirectory or found as an installed package. You
334can refer to the same [cmake_example]_ repository for a full sample project
335-- just swap out ``add_subdirectory`` for ``find_package``.
Lori A. Burns5cafc992016-12-13 10:55:38 -0500336
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100337.. _Config file: https://github.com/pybind/pybind11/blob/master/tools/pybind11Config.cmake.in
338
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100339
Henry Schreiner1729aae2020-08-19 12:26:26 -0400340.. _find-python-mode:
341
342FindPython mode
343---------------
344
345CMake 3.12+ (3.15+ recommended) added a new module called FindPython that had a
346highly improved search algorithm and modern targets and tools. If you use
347FindPython, pybind11 will detect this and use the existing targets instead:
Lori A. Burns5cafc992016-12-13 10:55:38 -0500348
349.. code-block:: cmake
350
Henry Schreiner1729aae2020-08-19 12:26:26 -0400351 cmake_minumum_required(VERSION 3.15...3.18)
352 project(example LANGUAGES CXX)
353
354 find_package(Python COMPONENTS Interpreter Development REQUIRED)
355 find_package(pybind11 CONFIG REQUIRED)
356 # or add_subdirectory(pybind11)
357
358 pybind11_add_module(example example.cpp)
359
360You can also use the targets (as listed below) with FindPython. If you define
361``PYBIND11_FINDPYTHON``, pybind11 will perform the FindPython step for you
362(mostly useful when building pybind11's own tests, or as a way to change search
363algorithms from the CMake invocation, with ``-DPYBIND11_FINDPYTHON=ON``.
364
365.. warning::
366
367 If you use FindPython2 and FindPython3 to dual-target Python, use the
368 individual targets listed below, and avoid targets that directly include
369 Python parts.
370
371There are `many ways to hint or force a discovery of a specific Python
372installation <https://cmake.org/cmake/help/latest/module/FindPython.html>`_),
373setting ``Python_ROOT_DIR`` may be the most common one (though with
374virtualenv/venv support, and Conda support, this tends to find the correct
375Python version more often than the old system did).
376
377.. versionadded:: 2.6
378
379Advanced: interface library targets
380-----------------------------------
381
382Pybind11 supports modern CMake usage patterns with a set of interface targets,
383available in all modes. The targets provided are:
384
385 ``pybind11::headers``
386 Just the pybind11 headers and minimum compile requirements
387
388 ``pybind11::python2_no_register``
389 Quiets the warning/error when mixing C++14 or higher and Python 2
390
391 ``pybind11::pybind11``
392 Python headers + ``pybind11::headers`` + ``pybind11::python2_no_register`` (Python 2 only)
393
394 ``pybind11::python_link_helper``
395 Just the "linking" part of pybind11:module
396
397 ``pybind11::module``
398 Everything for extension modules - ``pybind11::pybind11`` + ``Python::Module`` (FindPython CMake 3.15+) or ``pybind11::python_link_helper``
399
400 ``pybind11::embed``
401 Everything for embedding the Python interpreter - ``pybind11::pybind11`` + ``Python::Embed`` (FindPython) or Python libs
402
403 ``pybind11::lto`` / ``pybind11::thin_lto``
404 An alternative to `INTERPROCEDURAL_OPTIMIZATION` for adding link-time optimization.
405
406 ``pybind11::windows_extras``
407 ``/bigobj`` and ``/mp`` for MSVC.
408
Wenzel Jakob36c666f2020-09-04 23:31:05 +0200409 ``pybind11::opt_size``
410 ``/Os`` for MSVC, ``-Os`` for other compilers. Does nothing for debug builds.
411
Henry Schreiner1729aae2020-08-19 12:26:26 -0400412Two helper functions are also provided:
413
414 ``pybind11_strip(target)``
415 Strips a target (uses ``CMAKE_STRIP`` after the target is built)
416
417 ``pybind11_extension(target)``
418 Sets the correct extension (with SOABI) for a target.
419
420You can use these targets to build complex applications. For example, the
421``add_python_module`` function is identical to:
422
423.. code-block:: cmake
424
425 cmake_minimum_required(VERSION 3.4)
426 project(example LANGUAGES CXX)
Lori A. Burns5cafc992016-12-13 10:55:38 -0500427
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100428 find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11)
Lori A. Burns5cafc992016-12-13 10:55:38 -0500429
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100430 add_library(example MODULE main.cpp)
Henry Schreiner1729aae2020-08-19 12:26:26 -0400431
432 target_link_libraries(example PRIVATE pybind11::module pybind11::lto pybind11::windows_extras)
433
434 pybind11_extension(example)
435 pybind11_strip(example)
436
437 set_target_properties(example PROPERTIES CXX_VISIBILITY_PRESET "hidden"
438 CUDA_VISIBILITY_PRESET "hidden")
439
440Instead of setting properties, you can set ``CMAKE_*`` variables to initialize these correctly.
Lori A. Burns5cafc992016-12-13 10:55:38 -0500441
442.. warning::
443
444 Since pybind11 is a metatemplate library, it is crucial that certain
445 compiler flags are provided to ensure high quality code generation. In
446 contrast to the ``pybind11_add_module()`` command, the CMake interface
Henry Schreiner1729aae2020-08-19 12:26:26 -0400447 provides a *composable* set of targets to ensure that you retain flexibility.
448 It can be expecially important to provide or set these properties; the
449 :ref:`FAQ <faq:symhidden>` contains an explanation on why these are needed.
Lori A. Burns5cafc992016-12-13 10:55:38 -0500450
Henry Schreiner1729aae2020-08-19 12:26:26 -0400451.. versionadded:: 2.6
Wenzel Jakobf3de2d52016-12-26 13:34:28 +0100452
Henry Schreiner1729aae2020-08-19 12:26:26 -0400453.. _nopython-mode:
Henry Schreiner6ec17752020-07-28 00:43:12 -0400454
Henry Schreiner1729aae2020-08-19 12:26:26 -0400455Advanced: NOPYTHON mode
456-----------------------
Henry Schreiner6ec17752020-07-28 00:43:12 -0400457
Henry Schreiner1729aae2020-08-19 12:26:26 -0400458If you want complete control, you can set ``PYBIND11_NOPYTHON`` to completely
459disable Python integration (this also happens if you run ``FindPython2`` and
460``FindPython3`` without running ``FindPython``). This gives you complete
461freedom to integrate into an existing system (like `Scikit-Build's
462<https://scikit-build.readthedocs.io>`_ ``PythonExtensions``).
463``pybind11_add_module`` and ``pybind11_extension`` will be unavailable, and the
464targets will be missing any Python specific behavior.
Henry Schreiner6ec17752020-07-28 00:43:12 -0400465
Henry Schreiner1729aae2020-08-19 12:26:26 -0400466.. versionadded:: 2.6
Henry Schreiner6ec17752020-07-28 00:43:12 -0400467
Dean Moldovan6d2411f2017-04-22 23:24:13 +0200468Embedding the Python interpreter
469--------------------------------
470
471In addition to extension modules, pybind11 also supports embedding Python into
472a C++ executable or library. In CMake, simply link with the ``pybind11::embed``
473target. It provides everything needed to get the interpreter running. The Python
474headers and libraries are attached to the target. Unlike ``pybind11::module``,
475there is no need to manually set any additional properties here. For more
476information about usage in C++, see :doc:`/advanced/embedding`.
477
478.. code-block:: cmake
479
Henry Schreiner1729aae2020-08-19 12:26:26 -0400480 cmake_minimum_required(VERSION 3.4...3.18)
481 project(example LANGUAGES CXX)
Dean Moldovan6d2411f2017-04-22 23:24:13 +0200482
483 find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11)
484
Dean Moldovan8f6c1292017-05-31 13:48:39 +0200485 add_executable(example main.cpp)
Dean Moldovan6d2411f2017-04-22 23:24:13 +0200486 target_link_libraries(example PRIVATE pybind11::embed)
487
Ivan Smirnov5cbfda52017-08-30 20:58:43 +0100488.. _building_manually:
489
490Building manually
491=================
492
493pybind11 is a header-only library, hence it is not necessary to link against
494any special libraries and there are no intermediate (magic) translation steps.
495
496On Linux, you can compile an example such as the one given in
497:ref:`simple_example` using the following command:
498
499.. code-block:: bash
500
501 $ c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`
502
503The flags given here assume that you're using Python 3. For Python 2, just
504change the executable appropriately (to ``python`` or ``python2``).
505
506The ``python3 -m pybind11 --includes`` command fetches the include paths for
507both pybind11 and Python headers. This assumes that pybind11 has been installed
508using ``pip`` or ``conda``. If it hasn't, you can also manually specify
509``-I <path-to-pybind11>/include`` together with the Python includes path
510``python3-config --includes``.
511
512Note that Python 2.7 modules don't use a special suffix, so you should simply
513use ``example.so`` instead of ``example`python3-config --extension-suffix```.
514Besides, the ``--extension-suffix`` option may or may not be available, depending
515on the distribution; in the latter case, the module extension can be manually
516set to ``.so``.
517
Henry Schreinerfd61f502020-09-16 17:13:41 -0400518On macOS: the build command is almost the same but it also requires passing
Ivan Smirnov5cbfda52017-08-30 20:58:43 +0100519the ``-undefined dynamic_lookup`` flag so as to ignore missing symbols when
520building the module:
521
522.. code-block:: bash
523
524 $ c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`
525
526In general, it is advisable to include several additional build parameters
527that can considerably reduce the size of the created binary. Refer to section
528:ref:`cmake` for a detailed example of a suitable cross-platform CMake-based
529build system that works on all platforms including Windows.
530
531.. note::
532
533 On Linux and macOS, it's better to (intentionally) not link against
534 ``libpython``. The symbols will be resolved when the extension library
535 is loaded into a Python binary. This is preferable because you might
536 have several different installations of a given Python version (e.g. the
537 system-provided Python, and one that ships with a piece of commercial
538 software). In this way, the plugin will work with both versions, instead
539 of possibly importing a second Python library into a process that already
540 contains one (which will lead to a segfault).
Dean Moldovan6d2411f2017-04-22 23:24:13 +0200541
Griffin Downsa4cee362020-09-16 05:07:06 -0700542
Henry Schreinerdec33c22020-09-16 20:00:19 -0400543Building with Bazel
Griffin Downsa4cee362020-09-16 05:07:06 -0700544===================
Griffin Downsa4cee362020-09-16 05:07:06 -0700545
Henry Schreinerdec33c22020-09-16 20:00:19 -0400546You can build with the Bazel build system using the `pybind11_bazel
547<https://github.com/pybind/pybind11_bazel>`_ repository.
Griffin Downsa4cee362020-09-16 05:07:06 -0700548
Wenzel Jakobf3de2d52016-12-26 13:34:28 +0100549Generating binding code automatically
550=====================================
551
552The ``Binder`` project is a tool for automatic generation of pybind11 binding
553code by introspecting existing C++ codebases using LLVM/Clang. See the
554[binder]_ documentation for details.
555
556.. [binder] http://cppbinder.readthedocs.io/en/latest/about.html
Dustin Spicuzza2c4cd842019-11-24 02:36:48 -0500557
558[AutoWIG]_ is a Python library that wraps automatically compiled libraries into
559high-level languages. It parses C++ code using LLVM/Clang technologies and
560generates the wrappers using the Mako templating engine. The approach is automatic,
561extensible, and applies to very complex C++ libraries, composed of thousands of
562classes or incorporating modern meta-programming constructs.
563
564.. [AutoWIG] https://github.com/StatisKit/AutoWIG
Dustin Spicuzza6f3470f2020-08-10 16:10:45 -0400565
566[robotpy-build]_ is a is a pure python, cross platform build tool that aims to
567simplify creation of python wheels for pybind11 projects, and provide
568cross-project dependency management. Additionally, it is able to autogenerate
569customizable pybind11-based wrappers by parsing C++ header files.
570
571.. [robotpy-build] https://robotpy-build.readthedocs.io