Warning, /jana2/src/python/externals/pybind11-2.10.3/docs/compiling.rst is written in an unsupported language. File is not indexed.
0001 .. _compiling:
0002
0003 Build systems
0004 #############
0005
0006 .. _build-setuptools:
0007
0008 Building with setuptools
0009 ========================
0010
0011 For projects on PyPI, building with setuptools is the way to go. Sylvain Corlay
0012 has kindly provided an example project which shows how to set up everything,
0013 including automatic generation of documentation using Sphinx. Please refer to
0014 the [python_example]_ repository.
0015
0016 .. [python_example] https://github.com/pybind/python_example
0017
0018 A helper file is provided with pybind11 that can simplify usage with setuptools.
0019
0020 To use pybind11 inside your ``setup.py``, you have to have some system to
0021 ensure that ``pybind11`` is installed when you build your package. There are
0022 four possible ways to do this, and pybind11 supports all four: You can ask all
0023 users to install pybind11 beforehand (bad), you can use
0024 :ref:`setup_helpers-pep518` (good, but very new and requires Pip 10),
0025 :ref:`setup_helpers-setup_requires` (discouraged by Python packagers now that
0026 PEP 518 is available, but it still works everywhere), or you can
0027 :ref:`setup_helpers-copy-manually` (always works but you have to manually sync
0028 your copy to get updates).
0029
0030 An example of a ``setup.py`` using pybind11's helpers:
0031
0032 .. code-block:: python
0033
0034 from glob import glob
0035 from setuptools import setup
0036 from pybind11.setup_helpers import Pybind11Extension
0037
0038 ext_modules = [
0039 Pybind11Extension(
0040 "python_example",
0041 sorted(glob("src/*.cpp")), # Sort source files for reproducibility
0042 ),
0043 ]
0044
0045 setup(..., ext_modules=ext_modules)
0046
0047 If you want to do an automatic search for the highest supported C++ standard,
0048 that is supported via a ``build_ext`` command override; it will only affect
0049 ``Pybind11Extensions``:
0050
0051 .. code-block:: python
0052
0053 from glob import glob
0054 from setuptools import setup
0055 from pybind11.setup_helpers import Pybind11Extension, build_ext
0056
0057 ext_modules = [
0058 Pybind11Extension(
0059 "python_example",
0060 sorted(glob("src/*.cpp")),
0061 ),
0062 ]
0063
0064 setup(..., cmdclass={"build_ext": build_ext}, ext_modules=ext_modules)
0065
0066 If you have single-file extension modules that are directly stored in the
0067 Python source tree (``foo.cpp`` in the same directory as where a ``foo.py``
0068 would be located), you can also generate ``Pybind11Extensions`` using
0069 ``setup_helpers.intree_extensions``: ``intree_extensions(["path/to/foo.cpp",
0070 ...])`` returns a list of ``Pybind11Extensions`` which can be passed to
0071 ``ext_modules``, possibly after further customizing their attributes
0072 (``libraries``, ``include_dirs``, etc.). By doing so, a ``foo.*.so`` extension
0073 module will be generated and made available upon installation.
0074
0075 ``intree_extension`` will automatically detect if you are using a ``src``-style
0076 layout (as long as no namespace packages are involved), but you can also
0077 explicitly pass ``package_dir`` to it (as in ``setuptools.setup``).
0078
0079 Since pybind11 does not require NumPy when building, a light-weight replacement
0080 for NumPy's parallel compilation distutils tool is included. Use it like this:
0081
0082 .. code-block:: python
0083
0084 from pybind11.setup_helpers import ParallelCompile
0085
0086 # Optional multithreaded build
0087 ParallelCompile("NPY_NUM_BUILD_JOBS").install()
0088
0089 setup(...)
0090
0091 The argument is the name of an environment variable to control the number of
0092 threads, such as ``NPY_NUM_BUILD_JOBS`` (as used by NumPy), though you can set
0093 something different if you want; ``CMAKE_BUILD_PARALLEL_LEVEL`` is another choice
0094 a user might expect. You can also pass ``default=N`` to set the default number
0095 of threads (0 will take the number of threads available) and ``max=N``, the
0096 maximum number of threads; if you have a large extension you may want set this
0097 to a memory dependent number.
0098
0099 If you are developing rapidly and have a lot of C++ files, you may want to
0100 avoid rebuilding files that have not changed. For simple cases were you are
0101 using ``pip install -e .`` and do not have local headers, you can skip the
0102 rebuild if an object file is newer than its source (headers are not checked!)
0103 with the following:
0104
0105 .. code-block:: python
0106
0107 from pybind11.setup_helpers import ParallelCompile, naive_recompile
0108
0109 ParallelCompile("NPY_NUM_BUILD_JOBS", needs_recompile=naive_recompile).install()
0110
0111
0112 If you have a more complex build, you can implement a smarter function and pass
0113 it to ``needs_recompile``, or you can use [Ccache]_ instead. ``CXX="cache g++"
0114 pip install -e .`` would be the way to use it with GCC, for example. Unlike the
0115 simple solution, this even works even when not compiling in editable mode, but
0116 it does require Ccache to be installed.
0117
0118 Keep in mind that Pip will not even attempt to rebuild if it thinks it has
0119 already built a copy of your code, which it deduces from the version number.
0120 One way to avoid this is to use [setuptools_scm]_, which will generate a
0121 version number that includes the number of commits since your last tag and a
0122 hash for a dirty directory. Another way to force a rebuild is purge your cache
0123 or use Pip's ``--no-cache-dir`` option.
0124
0125 .. [Ccache] https://ccache.dev
0126
0127 .. [setuptools_scm] https://github.com/pypa/setuptools_scm
0128
0129 .. _setup_helpers-pep518:
0130
0131 PEP 518 requirements (Pip 10+ required)
0132 ---------------------------------------
0133
0134 If you use `PEP 518's <https://www.python.org/dev/peps/pep-0518/>`_
0135 ``pyproject.toml`` file, you can ensure that ``pybind11`` is available during
0136 the compilation of your project. When this file exists, Pip will make a new
0137 virtual environment, download just the packages listed here in ``requires=``,
0138 and build a wheel (binary Python package). It will then throw away the
0139 environment, and install your wheel.
0140
0141 Your ``pyproject.toml`` file will likely look something like this:
0142
0143 .. code-block:: toml
0144
0145 [build-system]
0146 requires = ["setuptools>=42", "wheel", "pybind11~=2.6.1"]
0147 build-backend = "setuptools.build_meta"
0148
0149 .. note::
0150
0151 The main drawback to this method is that a `PEP 517`_ compliant build tool,
0152 such as Pip 10+, is required for this approach to work; older versions of
0153 Pip completely ignore this file. If you distribute binaries (called wheels
0154 in Python) using something like `cibuildwheel`_, remember that ``setup.py``
0155 and ``pyproject.toml`` are not even contained in the wheel, so this high
0156 Pip requirement is only for source builds, and will not affect users of
0157 your binary wheels. If you are building SDists and wheels, then
0158 `pypa-build`_ is the recommended official tool.
0159
0160 .. _PEP 517: https://www.python.org/dev/peps/pep-0517/
0161 .. _cibuildwheel: https://cibuildwheel.readthedocs.io
0162 .. _pypa-build: https://pypa-build.readthedocs.io/en/latest/
0163
0164 .. _setup_helpers-setup_requires:
0165
0166 Classic ``setup_requires``
0167 --------------------------
0168
0169 If you want to support old versions of Pip with the classic
0170 ``setup_requires=["pybind11"]`` keyword argument to setup, which triggers a
0171 two-phase ``setup.py`` run, then you will need to use something like this to
0172 ensure the first pass works (which has not yet installed the ``setup_requires``
0173 packages, since it can't install something it does not know about):
0174
0175 .. code-block:: python
0176
0177 try:
0178 from pybind11.setup_helpers import Pybind11Extension
0179 except ImportError:
0180 from setuptools import Extension as Pybind11Extension
0181
0182
0183 It doesn't matter that the Extension class is not the enhanced subclass for the
0184 first pass run; and the second pass will have the ``setup_requires``
0185 requirements.
0186
0187 This is obviously more of a hack than the PEP 518 method, but it supports
0188 ancient versions of Pip.
0189
0190 .. _setup_helpers-copy-manually:
0191
0192 Copy manually
0193 -------------
0194
0195 You can also copy ``setup_helpers.py`` directly to your project; it was
0196 designed to be usable standalone, like the old example ``setup.py``. You can
0197 set ``include_pybind11=False`` to skip including the pybind11 package headers,
0198 so you can use it with git submodules and a specific git version. If you use
0199 this, you will need to import from a local file in ``setup.py`` and ensure the
0200 helper file is part of your MANIFEST.
0201
0202
0203 Closely related, if you include pybind11 as a subproject, you can run the
0204 ``setup_helpers.py`` inplace. If loaded correctly, this should even pick up
0205 the correct include for pybind11, though you can turn it off as shown above if
0206 you want to input it manually.
0207
0208 Suggested usage if you have pybind11 as a submodule in ``extern/pybind11``:
0209
0210 .. code-block:: python
0211
0212 DIR = os.path.abspath(os.path.dirname(__file__))
0213
0214 sys.path.append(os.path.join(DIR, "extern", "pybind11"))
0215 from pybind11.setup_helpers import Pybind11Extension # noqa: E402
0216
0217 del sys.path[-1]
0218
0219
0220 .. versionchanged:: 2.6
0221
0222 Added ``setup_helpers`` file.
0223
0224 Building with cppimport
0225 ========================
0226
0227 [cppimport]_ is a small Python import hook that determines whether there is a C++
0228 source file whose name matches the requested module. If there is, the file is
0229 compiled as a Python extension using pybind11 and placed in the same folder as
0230 the C++ source file. Python is then able to find the module and load it.
0231
0232 .. [cppimport] https://github.com/tbenthompson/cppimport
0233
0234 .. _cmake:
0235
0236 Building with CMake
0237 ===================
0238
0239 For C++ codebases that have an existing CMake-based build system, a Python
0240 extension module can be created with just a few lines of code:
0241
0242 .. code-block:: cmake
0243
0244 cmake_minimum_required(VERSION 3.4...3.18)
0245 project(example LANGUAGES CXX)
0246
0247 add_subdirectory(pybind11)
0248 pybind11_add_module(example example.cpp)
0249
0250 This assumes that the pybind11 repository is located in a subdirectory named
0251 :file:`pybind11` and that the code is located in a file named :file:`example.cpp`.
0252 The CMake command ``add_subdirectory`` will import the pybind11 project which
0253 provides the ``pybind11_add_module`` function. It will take care of all the
0254 details needed to build a Python extension module on any platform.
0255
0256 A working sample project, including a way to invoke CMake from :file:`setup.py` for
0257 PyPI integration, can be found in the [cmake_example]_ repository.
0258
0259 .. [cmake_example] https://github.com/pybind/cmake_example
0260
0261 .. versionchanged:: 2.6
0262 CMake 3.4+ is required.
0263
0264 Further information can be found at :doc:`cmake/index`.
0265
0266 pybind11_add_module
0267 -------------------
0268
0269 To ease the creation of Python extension modules, pybind11 provides a CMake
0270 function with the following signature:
0271
0272 .. code-block:: cmake
0273
0274 pybind11_add_module(<name> [MODULE | SHARED] [EXCLUDE_FROM_ALL]
0275 [NO_EXTRAS] [THIN_LTO] [OPT_SIZE] source1 [source2 ...])
0276
0277 This function behaves very much like CMake's builtin ``add_library`` (in fact,
0278 it's a wrapper function around that command). It will add a library target
0279 called ``<name>`` to be built from the listed source files. In addition, it
0280 will take care of all the Python-specific compiler and linker flags as well
0281 as the OS- and Python-version-specific file extension. The produced target
0282 ``<name>`` can be further manipulated with regular CMake commands.
0283
0284 ``MODULE`` or ``SHARED`` may be given to specify the type of library. If no
0285 type is given, ``MODULE`` is used by default which ensures the creation of a
0286 Python-exclusive module. Specifying ``SHARED`` will create a more traditional
0287 dynamic library which can also be linked from elsewhere. ``EXCLUDE_FROM_ALL``
0288 removes this target from the default build (see CMake docs for details).
0289
0290 Since pybind11 is a template library, ``pybind11_add_module`` adds compiler
0291 flags to ensure high quality code generation without bloat arising from long
0292 symbol names and duplication of code in different translation units. It
0293 sets default visibility to *hidden*, which is required for some pybind11
0294 features and functionality when attempting to load multiple pybind11 modules
0295 compiled under different pybind11 versions. It also adds additional flags
0296 enabling LTO (Link Time Optimization) and strip unneeded symbols. See the
0297 :ref:`FAQ entry <faq:symhidden>` for a more detailed explanation. These
0298 latter optimizations are never applied in ``Debug`` mode. If ``NO_EXTRAS`` is
0299 given, they will always be disabled, even in ``Release`` mode. However, this
0300 will result in code bloat and is generally not recommended.
0301
0302 As stated above, LTO is enabled by default. Some newer compilers also support
0303 different flavors of LTO such as `ThinLTO`_. Setting ``THIN_LTO`` will cause
0304 the function to prefer this flavor if available. The function falls back to
0305 regular LTO if ``-flto=thin`` is not available. If
0306 ``CMAKE_INTERPROCEDURAL_OPTIMIZATION`` is set (either ``ON`` or ``OFF``), then
0307 that will be respected instead of the built-in flag search.
0308
0309 .. note::
0310
0311 If you want to set the property form on targets or the
0312 ``CMAKE_INTERPROCEDURAL_OPTIMIZATION_<CONFIG>`` versions of this, you should
0313 still use ``set(CMAKE_INTERPROCEDURAL_OPTIMIZATION OFF)`` (otherwise a
0314 no-op) to disable pybind11's ipo flags.
0315
0316 The ``OPT_SIZE`` flag enables size-based optimization equivalent to the
0317 standard ``/Os`` or ``-Os`` compiler flags and the ``MinSizeRel`` build type,
0318 which avoid optimizations that that can substantially increase the size of the
0319 resulting binary. This flag is particularly useful in projects that are split
0320 into performance-critical parts and associated bindings. In this case, we can
0321 compile the project in release mode (and hence, optimize performance globally),
0322 and specify ``OPT_SIZE`` for the binding target, where size might be the main
0323 concern as performance is often less critical here. A ~25% size reduction has
0324 been observed in practice. This flag only changes the optimization behavior at
0325 a per-target level and takes precedence over the global CMake build type
0326 (``Release``, ``RelWithDebInfo``) except for ``Debug`` builds, where
0327 optimizations remain disabled.
0328
0329 .. _ThinLTO: http://clang.llvm.org/docs/ThinLTO.html
0330
0331 Configuration variables
0332 -----------------------
0333
0334 By default, pybind11 will compile modules with the compiler default or the
0335 minimum standard required by pybind11, whichever is higher. You can set the
0336 standard explicitly with
0337 `CMAKE_CXX_STANDARD <https://cmake.org/cmake/help/latest/variable/CMAKE_CXX_STANDARD.html>`_:
0338
0339 .. code-block:: cmake
0340
0341 set(CMAKE_CXX_STANDARD 14 CACHE STRING "C++ version selection") # or 11, 14, 17, 20
0342 set(CMAKE_CXX_STANDARD_REQUIRED ON) # optional, ensure standard is supported
0343 set(CMAKE_CXX_EXTENSIONS OFF) # optional, keep compiler extensions off
0344
0345 The variables can also be set when calling CMake from the command line using
0346 the ``-D<variable>=<value>`` flag. You can also manually set ``CXX_STANDARD``
0347 on a target or use ``target_compile_features`` on your targets - anything that
0348 CMake supports.
0349
0350 Classic Python support: The target Python version can be selected by setting
0351 ``PYBIND11_PYTHON_VERSION`` or an exact Python installation can be specified
0352 with ``PYTHON_EXECUTABLE``. For example:
0353
0354 .. code-block:: bash
0355
0356 cmake -DPYBIND11_PYTHON_VERSION=3.6 ..
0357
0358 # Another method:
0359 cmake -DPYTHON_EXECUTABLE=/path/to/python ..
0360
0361 # This often is a good way to get the current Python, works in environments:
0362 cmake -DPYTHON_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)") ..
0363
0364
0365 find_package vs. add_subdirectory
0366 ---------------------------------
0367
0368 For CMake-based projects that don't include the pybind11 repository internally,
0369 an external installation can be detected through ``find_package(pybind11)``.
0370 See the `Config file`_ docstring for details of relevant CMake variables.
0371
0372 .. code-block:: cmake
0373
0374 cmake_minimum_required(VERSION 3.4...3.18)
0375 project(example LANGUAGES CXX)
0376
0377 find_package(pybind11 REQUIRED)
0378 pybind11_add_module(example example.cpp)
0379
0380 Note that ``find_package(pybind11)`` will only work correctly if pybind11
0381 has been correctly installed on the system, e. g. after downloading or cloning
0382 the pybind11 repository :
0383
0384 .. code-block:: bash
0385
0386 # Classic CMake
0387 cd pybind11
0388 mkdir build
0389 cd build
0390 cmake ..
0391 make install
0392
0393 # CMake 3.15+
0394 cd pybind11
0395 cmake -S . -B build
0396 cmake --build build -j 2 # Build on 2 cores
0397 cmake --install build
0398
0399 Once detected, the aforementioned ``pybind11_add_module`` can be employed as
0400 before. The function usage and configuration variables are identical no matter
0401 if pybind11 is added as a subdirectory or found as an installed package. You
0402 can refer to the same [cmake_example]_ repository for a full sample project
0403 -- just swap out ``add_subdirectory`` for ``find_package``.
0404
0405 .. _Config file: https://github.com/pybind/pybind11/blob/master/tools/pybind11Config.cmake.in
0406
0407
0408 .. _find-python-mode:
0409
0410 FindPython mode
0411 ---------------
0412
0413 CMake 3.12+ (3.15+ recommended, 3.18.2+ ideal) added a new module called
0414 FindPython that had a highly improved search algorithm and modern targets
0415 and tools. If you use FindPython, pybind11 will detect this and use the
0416 existing targets instead:
0417
0418 .. code-block:: cmake
0419
0420 cmake_minimum_required(VERSION 3.15...3.22)
0421 project(example LANGUAGES CXX)
0422
0423 find_package(Python 3.6 COMPONENTS Interpreter Development REQUIRED)
0424 find_package(pybind11 CONFIG REQUIRED)
0425 # or add_subdirectory(pybind11)
0426
0427 pybind11_add_module(example example.cpp)
0428
0429 You can also use the targets (as listed below) with FindPython. If you define
0430 ``PYBIND11_FINDPYTHON``, pybind11 will perform the FindPython step for you
0431 (mostly useful when building pybind11's own tests, or as a way to change search
0432 algorithms from the CMake invocation, with ``-DPYBIND11_FINDPYTHON=ON``.
0433
0434 .. warning::
0435
0436 If you use FindPython to multi-target Python versions, use the individual
0437 targets listed below, and avoid targets that directly include Python parts.
0438
0439 There are `many ways to hint or force a discovery of a specific Python
0440 installation <https://cmake.org/cmake/help/latest/module/FindPython.html>`_),
0441 setting ``Python_ROOT_DIR`` may be the most common one (though with
0442 virtualenv/venv support, and Conda support, this tends to find the correct
0443 Python version more often than the old system did).
0444
0445 .. warning::
0446
0447 When the Python libraries (i.e. ``libpythonXX.a`` and ``libpythonXX.so``
0448 on Unix) are not available, as is the case on a manylinux image, the
0449 ``Development`` component will not be resolved by ``FindPython``. When not
0450 using the embedding functionality, CMake 3.18+ allows you to specify
0451 ``Development.Module`` instead of ``Development`` to resolve this issue.
0452
0453 .. versionadded:: 2.6
0454
0455 Advanced: interface library targets
0456 -----------------------------------
0457
0458 Pybind11 supports modern CMake usage patterns with a set of interface targets,
0459 available in all modes. The targets provided are:
0460
0461 ``pybind11::headers``
0462 Just the pybind11 headers and minimum compile requirements
0463
0464 ``pybind11::pybind11``
0465 Python headers + ``pybind11::headers``
0466
0467 ``pybind11::python_link_helper``
0468 Just the "linking" part of pybind11:module
0469
0470 ``pybind11::module``
0471 Everything for extension modules - ``pybind11::pybind11`` + ``Python::Module`` (FindPython CMake 3.15+) or ``pybind11::python_link_helper``
0472
0473 ``pybind11::embed``
0474 Everything for embedding the Python interpreter - ``pybind11::pybind11`` + ``Python::Python`` (FindPython) or Python libs
0475
0476 ``pybind11::lto`` / ``pybind11::thin_lto``
0477 An alternative to `INTERPROCEDURAL_OPTIMIZATION` for adding link-time optimization.
0478
0479 ``pybind11::windows_extras``
0480 ``/bigobj`` and ``/mp`` for MSVC.
0481
0482 ``pybind11::opt_size``
0483 ``/Os`` for MSVC, ``-Os`` for other compilers. Does nothing for debug builds.
0484
0485 Two helper functions are also provided:
0486
0487 ``pybind11_strip(target)``
0488 Strips a target (uses ``CMAKE_STRIP`` after the target is built)
0489
0490 ``pybind11_extension(target)``
0491 Sets the correct extension (with SOABI) for a target.
0492
0493 You can use these targets to build complex applications. For example, the
0494 ``add_python_module`` function is identical to:
0495
0496 .. code-block:: cmake
0497
0498 cmake_minimum_required(VERSION 3.4)
0499 project(example LANGUAGES CXX)
0500
0501 find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11)
0502
0503 add_library(example MODULE main.cpp)
0504
0505 target_link_libraries(example PRIVATE pybind11::module pybind11::lto pybind11::windows_extras)
0506
0507 pybind11_extension(example)
0508 if(NOT MSVC AND NOT ${CMAKE_BUILD_TYPE} MATCHES Debug|RelWithDebInfo)
0509 # Strip unnecessary sections of the binary on Linux/macOS
0510 pybind11_strip(example)
0511 endif()
0512
0513 set_target_properties(example PROPERTIES CXX_VISIBILITY_PRESET "hidden"
0514 CUDA_VISIBILITY_PRESET "hidden")
0515
0516 Instead of setting properties, you can set ``CMAKE_*`` variables to initialize these correctly.
0517
0518 .. warning::
0519
0520 Since pybind11 is a metatemplate library, it is crucial that certain
0521 compiler flags are provided to ensure high quality code generation. In
0522 contrast to the ``pybind11_add_module()`` command, the CMake interface
0523 provides a *composable* set of targets to ensure that you retain flexibility.
0524 It can be especially important to provide or set these properties; the
0525 :ref:`FAQ <faq:symhidden>` contains an explanation on why these are needed.
0526
0527 .. versionadded:: 2.6
0528
0529 .. _nopython-mode:
0530
0531 Advanced: NOPYTHON mode
0532 -----------------------
0533
0534 If you want complete control, you can set ``PYBIND11_NOPYTHON`` to completely
0535 disable Python integration (this also happens if you run ``FindPython2`` and
0536 ``FindPython3`` without running ``FindPython``). This gives you complete
0537 freedom to integrate into an existing system (like `Scikit-Build's
0538 <https://scikit-build.readthedocs.io>`_ ``PythonExtensions``).
0539 ``pybind11_add_module`` and ``pybind11_extension`` will be unavailable, and the
0540 targets will be missing any Python specific behavior.
0541
0542 .. versionadded:: 2.6
0543
0544 Embedding the Python interpreter
0545 --------------------------------
0546
0547 In addition to extension modules, pybind11 also supports embedding Python into
0548 a C++ executable or library. In CMake, simply link with the ``pybind11::embed``
0549 target. It provides everything needed to get the interpreter running. The Python
0550 headers and libraries are attached to the target. Unlike ``pybind11::module``,
0551 there is no need to manually set any additional properties here. For more
0552 information about usage in C++, see :doc:`/advanced/embedding`.
0553
0554 .. code-block:: cmake
0555
0556 cmake_minimum_required(VERSION 3.4...3.18)
0557 project(example LANGUAGES CXX)
0558
0559 find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11)
0560
0561 add_executable(example main.cpp)
0562 target_link_libraries(example PRIVATE pybind11::embed)
0563
0564 .. _building_manually:
0565
0566 Building manually
0567 =================
0568
0569 pybind11 is a header-only library, hence it is not necessary to link against
0570 any special libraries and there are no intermediate (magic) translation steps.
0571
0572 On Linux, you can compile an example such as the one given in
0573 :ref:`simple_example` using the following command:
0574
0575 .. code-block:: bash
0576
0577 $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
0578
0579 The ``python3 -m pybind11 --includes`` command fetches the include paths for
0580 both pybind11 and Python headers. This assumes that pybind11 has been installed
0581 using ``pip`` or ``conda``. If it hasn't, you can also manually specify
0582 ``-I <path-to-pybind11>/include`` together with the Python includes path
0583 ``python3-config --includes``.
0584
0585 On macOS: the build command is almost the same but it also requires passing
0586 the ``-undefined dynamic_lookup`` flag so as to ignore missing symbols when
0587 building the module:
0588
0589 .. code-block:: bash
0590
0591 $ c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
0592
0593 In general, it is advisable to include several additional build parameters
0594 that can considerably reduce the size of the created binary. Refer to section
0595 :ref:`cmake` for a detailed example of a suitable cross-platform CMake-based
0596 build system that works on all platforms including Windows.
0597
0598 .. note::
0599
0600 On Linux and macOS, it's better to (intentionally) not link against
0601 ``libpython``. The symbols will be resolved when the extension library
0602 is loaded into a Python binary. This is preferable because you might
0603 have several different installations of a given Python version (e.g. the
0604 system-provided Python, and one that ships with a piece of commercial
0605 software). In this way, the plugin will work with both versions, instead
0606 of possibly importing a second Python library into a process that already
0607 contains one (which will lead to a segfault).
0608
0609
0610 Building with Bazel
0611 ===================
0612
0613 You can build with the Bazel build system using the `pybind11_bazel
0614 <https://github.com/pybind/pybind11_bazel>`_ repository.
0615
0616 Generating binding code automatically
0617 =====================================
0618
0619 The ``Binder`` project is a tool for automatic generation of pybind11 binding
0620 code by introspecting existing C++ codebases using LLVM/Clang. See the
0621 [binder]_ documentation for details.
0622
0623 .. [binder] http://cppbinder.readthedocs.io/en/latest/about.html
0624
0625 [AutoWIG]_ is a Python library that wraps automatically compiled libraries into
0626 high-level languages. It parses C++ code using LLVM/Clang technologies and
0627 generates the wrappers using the Mako templating engine. The approach is automatic,
0628 extensible, and applies to very complex C++ libraries, composed of thousands of
0629 classes or incorporating modern meta-programming constructs.
0630
0631 .. [AutoWIG] https://github.com/StatisKit/AutoWIG
0632
0633 [robotpy-build]_ is a is a pure python, cross platform build tool that aims to
0634 simplify creation of python wheels for pybind11 projects, and provide
0635 cross-project dependency management. Additionally, it is able to autogenerate
0636 customizable pybind11-based wrappers by parsing C++ header files.
0637
0638 .. [robotpy-build] https://robotpy-build.readthedocs.io