blob: 72b0c1eecf352e4ae6657cd6c5293542eba63ec5 [file] [log] [blame]
Ivan Smirnov5cbfda52017-08-30 20:58:43 +01001.. _compiling:
2
Wenzel Jakob4a48afb2016-03-09 21:31:21 +01003Build systems
4#############
5
6Building with setuptools
7========================
8
9For projects on PyPI, building with setuptools is the way to go. Sylvain Corlay
10has kindly provided an example project which shows how to set up everything,
11including automatic generation of documentation using Sphinx. Please refer to
Wenzel Jakobca8dc082016-06-03 14:24:17 +020012the [python_example]_ repository.
Wenzel Jakob4a48afb2016-03-09 21:31:21 +010013
Wenzel Jakobca8dc082016-06-03 14:24:17 +020014.. [python_example] https://github.com/pybind/python_example
Wenzel Jakob4a48afb2016-03-09 21:31:21 +010015
Wenzel Jakoba439cca2016-05-17 10:47:52 +020016Building with cppimport
17========================
18
Dean Moldovan8665ee82017-08-17 15:01:43 +020019[cppimport]_ is a small Python import hook that determines whether there is a C++
20source file whose name matches the requested module. If there is, the file is
21compiled as a Python extension using pybind11 and placed in the same folder as
22the C++ source file. Python is then able to find the module and load it.
Wenzel Jakoba439cca2016-05-17 10:47:52 +020023
24.. [cppimport] https://github.com/tbenthompson/cppimport
25
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020026.. _cmake:
27
28Building with CMake
29===================
30
Wenzel Jakobfe342412016-09-06 13:02:29 +090031For C++ codebases that have an existing CMake-based build system, a Python
Dean Moldovan24ddf4b2016-05-27 00:11:52 +020032extension module can be created with just a few lines of code:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020033
34.. code-block:: cmake
35
Henry Schreiner1729aae2020-08-19 12:26:26 -040036 cmake_minimum_required(VERSION 3.4...3.18)
37 project(example LANGUAGES CXX)
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020038
Dean Moldovan24ddf4b2016-05-27 00:11:52 +020039 add_subdirectory(pybind11)
40 pybind11_add_module(example example.cpp)
Wenzel Jakobf64feaf2016-04-28 14:33:45 +020041
Wenzel Jakobfe342412016-09-06 13:02:29 +090042This assumes that the pybind11 repository is located in a subdirectory named
Dean Moldovan24ddf4b2016-05-27 00:11:52 +020043:file:`pybind11` and that the code is located in a file named :file:`example.cpp`.
Dean Moldovan0cbec5c2016-12-16 22:58:37 +010044The CMake command ``add_subdirectory`` will import the pybind11 project which
45provides the ``pybind11_add_module`` function. It will take care of all the
46details needed to build a Python extension module on any platform.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020047
Dean Moldovan24ddf4b2016-05-27 00:11:52 +020048A working sample project, including a way to invoke CMake from :file:`setup.py` for
49PyPI integration, can be found in the [cmake_example]_ repository.
Wenzel Jakobcaa9d442016-01-17 22:36:34 +010050
Wenzel Jakobaa79af02016-06-03 12:23:24 +020051.. [cmake_example] https://github.com/pybind/cmake_example
Lori A. Burns5cafc992016-12-13 10:55:38 -050052
Henry Schreiner1729aae2020-08-19 12:26:26 -040053.. versionchanged:: 2.6
54 CMake 3.4+ is required.
55
Dean Moldovan0cbec5c2016-12-16 22:58:37 +010056pybind11_add_module
57-------------------
Lori A. Burns5cafc992016-12-13 10:55:38 -050058
Dean Moldovan0cbec5c2016-12-16 22:58:37 +010059To ease the creation of Python extension modules, pybind11 provides a CMake
60function with the following signature:
61
62.. code-block:: cmake
63
64 pybind11_add_module(<name> [MODULE | SHARED] [EXCLUDE_FROM_ALL]
Henry Schreiner6ec17752020-07-28 00:43:12 -040065 [NO_EXTRAS] [THIN_LTO] source1 [source2 ...])
Dean Moldovan0cbec5c2016-12-16 22:58:37 +010066
67This function behaves very much like CMake's builtin ``add_library`` (in fact,
68it's a wrapper function around that command). It will add a library target
69called ``<name>`` to be built from the listed source files. In addition, it
70will take care of all the Python-specific compiler and linker flags as well
71as the OS- and Python-version-specific file extension. The produced target
72``<name>`` can be further manipulated with regular CMake commands.
73
74``MODULE`` or ``SHARED`` may be given to specify the type of library. If no
75type is given, ``MODULE`` is used by default which ensures the creation of a
76Python-exclusive module. Specifying ``SHARED`` will create a more traditional
77dynamic library which can also be linked from elsewhere. ``EXCLUDE_FROM_ALL``
78removes this target from the default build (see CMake docs for details).
79
80Since pybind11 is a template library, ``pybind11_add_module`` adds compiler
81flags to ensure high quality code generation without bloat arising from long
Jason Rhinelander97aa54f2017-08-10 12:08:42 -040082symbol names and duplication of code in different translation units. It
83sets default visibility to *hidden*, which is required for some pybind11
84features and functionality when attempting to load multiple pybind11 modules
85compiled under different pybind11 versions. It also adds additional flags
86enabling LTO (Link Time Optimization) and strip unneeded symbols. See the
87:ref:`FAQ entry <faq:symhidden>` for a more detailed explanation. These
88latter optimizations are never applied in ``Debug`` mode. If ``NO_EXTRAS`` is
89given, they will always be disabled, even in ``Release`` mode. However, this
90will result in code bloat and is generally not recommended.
Dean Moldovan0cbec5c2016-12-16 22:58:37 +010091
92As stated above, LTO is enabled by default. Some newer compilers also support
93different flavors of LTO such as `ThinLTO`_. Setting ``THIN_LTO`` will cause
94the function to prefer this flavor if available. The function falls back to
Henry Schreiner1729aae2020-08-19 12:26:26 -040095regular LTO if ``-flto=thin`` is not available. If
96``CMAKE_INTERPROCEDURAL_OPTIMIZATION`` is set (either ON or OFF), then that
97will be respected instead of the built-in flag search.
Dean Moldovan0cbec5c2016-12-16 22:58:37 +010098
99.. _ThinLTO: http://clang.llvm.org/docs/ThinLTO.html
100
101Configuration variables
102-----------------------
103
Henry Schreiner6ec17752020-07-28 00:43:12 -0400104By default, pybind11 will compile modules with the compiler default or the
Henry Schreiner1651c322020-07-30 16:04:26 -0400105minimum standard required by pybind11, whichever is higher. You can set the
Henry Schreiner6ec17752020-07-28 00:43:12 -0400106standard explicitly with
107`CMAKE_CXX_STANDARD <https://cmake.org/cmake/help/latest/variable/CMAKE_CXX_STANDARD.html>`_:
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100108
109.. code-block:: cmake
110
Henry Schreiner1b92cd12020-07-29 15:02:53 -0400111 set(CMAKE_CXX_STANDARD 14) # or 11, 14, 17, 20
112 set(CMAKE_CXX_STANDARD_REQUIRED ON) # optional, ensure standard is supported
113 set(CMAKE_CXX_EXTENSIONS OFF) # optional, keep compiler extensionsn off
Jason Rhinelander77710ff2017-05-09 14:37:48 -0400114
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100115
Henry Schreiner6ec17752020-07-28 00:43:12 -0400116The variables can also be set when calling CMake from the command line using
117the ``-D<variable>=<value>`` flag. You can also manually set ``CXX_STANDARD``
118on a target or use ``target_compile_features`` on your targets - anything that
119CMake supports.
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100120
Henry Schreiner1729aae2020-08-19 12:26:26 -0400121Classic Python support: The target Python version can be selected by setting
122``PYBIND11_PYTHON_VERSION`` or an exact Python installation can be specified
123with ``PYTHON_EXECUTABLE``. For example:
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100124
125.. code-block:: bash
126
127 cmake -DPYBIND11_PYTHON_VERSION=3.6 ..
Henry Schreiner1b92cd12020-07-29 15:02:53 -0400128
129 # Another method:
130 cmake -DPYTHON_EXECUTABLE=/path/to/python ..
131
Henry Schreiner1651c322020-07-30 16:04:26 -0400132 # This often is a good way to get the current Python, works in environments:
Henry Schreiner6ec17752020-07-28 00:43:12 -0400133 cmake -DPYTHON_EXECUTABLE=$(python3 -c "import sys; print(sys.executable)") ..
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100134
Henry Schreiner1729aae2020-08-19 12:26:26 -0400135
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100136find_package vs. add_subdirectory
137---------------------------------
138
139For CMake-based projects that don't include the pybind11 repository internally,
140an external installation can be detected through ``find_package(pybind11)``.
141See the `Config file`_ docstring for details of relevant CMake variables.
Lori A. Burns5cafc992016-12-13 10:55:38 -0500142
143.. code-block:: cmake
144
Henry Schreiner1729aae2020-08-19 12:26:26 -0400145 cmake_minimum_required(VERSION 3.4...3.18)
146 project(example LANGUAGES CXX)
Lori A. Burns5cafc992016-12-13 10:55:38 -0500147
148 find_package(pybind11 REQUIRED)
149 pybind11_add_module(example example.cpp)
150
nstelzenc2514342019-06-10 16:35:36 +0200151Note that ``find_package(pybind11)`` will only work correctly if pybind11
152has been correctly installed on the system, e. g. after downloading or cloning
153the pybind11 repository :
154
155.. code-block:: bash
156
Henry Schreiner1b92cd12020-07-29 15:02:53 -0400157 # Classic CMake
nstelzenc2514342019-06-10 16:35:36 +0200158 cd pybind11
159 mkdir build
160 cd build
161 cmake ..
162 make install
163
Henry Schreiner1b92cd12020-07-29 15:02:53 -0400164 # CMake 3.15+
165 cd pybind11
166 cmake -S . -B build
167 cmake --build build -j 2 # Build on 2 cores
168 cmake --install build
169
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100170Once detected, the aforementioned ``pybind11_add_module`` can be employed as
171before. The function usage and configuration variables are identical no matter
172if pybind11 is added as a subdirectory or found as an installed package. You
173can refer to the same [cmake_example]_ repository for a full sample project
174-- just swap out ``add_subdirectory`` for ``find_package``.
Lori A. Burns5cafc992016-12-13 10:55:38 -0500175
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100176.. _Config file: https://github.com/pybind/pybind11/blob/master/tools/pybind11Config.cmake.in
177
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100178
Henry Schreiner1729aae2020-08-19 12:26:26 -0400179.. _find-python-mode:
180
181FindPython mode
182---------------
183
184CMake 3.12+ (3.15+ recommended) added a new module called FindPython that had a
185highly improved search algorithm and modern targets and tools. If you use
186FindPython, pybind11 will detect this and use the existing targets instead:
Lori A. Burns5cafc992016-12-13 10:55:38 -0500187
188.. code-block:: cmake
189
Henry Schreiner1729aae2020-08-19 12:26:26 -0400190 cmake_minumum_required(VERSION 3.15...3.18)
191 project(example LANGUAGES CXX)
192
193 find_package(Python COMPONENTS Interpreter Development REQUIRED)
194 find_package(pybind11 CONFIG REQUIRED)
195 # or add_subdirectory(pybind11)
196
197 pybind11_add_module(example example.cpp)
198
199You can also use the targets (as listed below) with FindPython. If you define
200``PYBIND11_FINDPYTHON``, pybind11 will perform the FindPython step for you
201(mostly useful when building pybind11's own tests, or as a way to change search
202algorithms from the CMake invocation, with ``-DPYBIND11_FINDPYTHON=ON``.
203
204.. warning::
205
206 If you use FindPython2 and FindPython3 to dual-target Python, use the
207 individual targets listed below, and avoid targets that directly include
208 Python parts.
209
210There are `many ways to hint or force a discovery of a specific Python
211installation <https://cmake.org/cmake/help/latest/module/FindPython.html>`_),
212setting ``Python_ROOT_DIR`` may be the most common one (though with
213virtualenv/venv support, and Conda support, this tends to find the correct
214Python version more often than the old system did).
215
216.. versionadded:: 2.6
217
218Advanced: interface library targets
219-----------------------------------
220
221Pybind11 supports modern CMake usage patterns with a set of interface targets,
222available in all modes. The targets provided are:
223
224 ``pybind11::headers``
225 Just the pybind11 headers and minimum compile requirements
226
227 ``pybind11::python2_no_register``
228 Quiets the warning/error when mixing C++14 or higher and Python 2
229
230 ``pybind11::pybind11``
231 Python headers + ``pybind11::headers`` + ``pybind11::python2_no_register`` (Python 2 only)
232
233 ``pybind11::python_link_helper``
234 Just the "linking" part of pybind11:module
235
236 ``pybind11::module``
237 Everything for extension modules - ``pybind11::pybind11`` + ``Python::Module`` (FindPython CMake 3.15+) or ``pybind11::python_link_helper``
238
239 ``pybind11::embed``
240 Everything for embedding the Python interpreter - ``pybind11::pybind11`` + ``Python::Embed`` (FindPython) or Python libs
241
242 ``pybind11::lto`` / ``pybind11::thin_lto``
243 An alternative to `INTERPROCEDURAL_OPTIMIZATION` for adding link-time optimization.
244
245 ``pybind11::windows_extras``
246 ``/bigobj`` and ``/mp`` for MSVC.
247
248Two helper functions are also provided:
249
250 ``pybind11_strip(target)``
251 Strips a target (uses ``CMAKE_STRIP`` after the target is built)
252
253 ``pybind11_extension(target)``
254 Sets the correct extension (with SOABI) for a target.
255
256You can use these targets to build complex applications. For example, the
257``add_python_module`` function is identical to:
258
259.. code-block:: cmake
260
261 cmake_minimum_required(VERSION 3.4)
262 project(example LANGUAGES CXX)
Lori A. Burns5cafc992016-12-13 10:55:38 -0500263
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100264 find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11)
Lori A. Burns5cafc992016-12-13 10:55:38 -0500265
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100266 add_library(example MODULE main.cpp)
Henry Schreiner1729aae2020-08-19 12:26:26 -0400267
268 target_link_libraries(example PRIVATE pybind11::module pybind11::lto pybind11::windows_extras)
269
270 pybind11_extension(example)
271 pybind11_strip(example)
272
273 set_target_properties(example PROPERTIES CXX_VISIBILITY_PRESET "hidden"
274 CUDA_VISIBILITY_PRESET "hidden")
275
276Instead of setting properties, you can set ``CMAKE_*`` variables to initialize these correctly.
Lori A. Burns5cafc992016-12-13 10:55:38 -0500277
278.. warning::
279
280 Since pybind11 is a metatemplate library, it is crucial that certain
281 compiler flags are provided to ensure high quality code generation. In
282 contrast to the ``pybind11_add_module()`` command, the CMake interface
Henry Schreiner1729aae2020-08-19 12:26:26 -0400283 provides a *composable* set of targets to ensure that you retain flexibility.
284 It can be expecially important to provide or set these properties; the
285 :ref:`FAQ <faq:symhidden>` contains an explanation on why these are needed.
Lori A. Burns5cafc992016-12-13 10:55:38 -0500286
Henry Schreiner1729aae2020-08-19 12:26:26 -0400287.. versionadded:: 2.6
Wenzel Jakobf3de2d52016-12-26 13:34:28 +0100288
Henry Schreiner1729aae2020-08-19 12:26:26 -0400289.. _nopython-mode:
Henry Schreiner6ec17752020-07-28 00:43:12 -0400290
Henry Schreiner1729aae2020-08-19 12:26:26 -0400291Advanced: NOPYTHON mode
292-----------------------
Henry Schreiner6ec17752020-07-28 00:43:12 -0400293
Henry Schreiner1729aae2020-08-19 12:26:26 -0400294If you want complete control, you can set ``PYBIND11_NOPYTHON`` to completely
295disable Python integration (this also happens if you run ``FindPython2`` and
296``FindPython3`` without running ``FindPython``). This gives you complete
297freedom to integrate into an existing system (like `Scikit-Build's
298<https://scikit-build.readthedocs.io>`_ ``PythonExtensions``).
299``pybind11_add_module`` and ``pybind11_extension`` will be unavailable, and the
300targets will be missing any Python specific behavior.
Henry Schreiner6ec17752020-07-28 00:43:12 -0400301
Henry Schreiner1729aae2020-08-19 12:26:26 -0400302.. versionadded:: 2.6
Henry Schreiner6ec17752020-07-28 00:43:12 -0400303
Dean Moldovan6d2411f2017-04-22 23:24:13 +0200304Embedding the Python interpreter
305--------------------------------
306
307In addition to extension modules, pybind11 also supports embedding Python into
308a C++ executable or library. In CMake, simply link with the ``pybind11::embed``
309target. It provides everything needed to get the interpreter running. The Python
310headers and libraries are attached to the target. Unlike ``pybind11::module``,
311there is no need to manually set any additional properties here. For more
312information about usage in C++, see :doc:`/advanced/embedding`.
313
314.. code-block:: cmake
315
Henry Schreiner1729aae2020-08-19 12:26:26 -0400316 cmake_minimum_required(VERSION 3.4...3.18)
317 project(example LANGUAGES CXX)
Dean Moldovan6d2411f2017-04-22 23:24:13 +0200318
319 find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11)
320
Dean Moldovan8f6c1292017-05-31 13:48:39 +0200321 add_executable(example main.cpp)
Dean Moldovan6d2411f2017-04-22 23:24:13 +0200322 target_link_libraries(example PRIVATE pybind11::embed)
323
Ivan Smirnov5cbfda52017-08-30 20:58:43 +0100324.. _building_manually:
325
326Building manually
327=================
328
329pybind11 is a header-only library, hence it is not necessary to link against
330any special libraries and there are no intermediate (magic) translation steps.
331
332On Linux, you can compile an example such as the one given in
333:ref:`simple_example` using the following command:
334
335.. code-block:: bash
336
337 $ c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`
338
339The flags given here assume that you're using Python 3. For Python 2, just
340change the executable appropriately (to ``python`` or ``python2``).
341
342The ``python3 -m pybind11 --includes`` command fetches the include paths for
343both pybind11 and Python headers. This assumes that pybind11 has been installed
344using ``pip`` or ``conda``. If it hasn't, you can also manually specify
345``-I <path-to-pybind11>/include`` together with the Python includes path
346``python3-config --includes``.
347
348Note that Python 2.7 modules don't use a special suffix, so you should simply
349use ``example.so`` instead of ``example`python3-config --extension-suffix```.
350Besides, the ``--extension-suffix`` option may or may not be available, depending
351on the distribution; in the latter case, the module extension can be manually
352set to ``.so``.
353
354On Mac OS: the build command is almost the same but it also requires passing
355the ``-undefined dynamic_lookup`` flag so as to ignore missing symbols when
356building the module:
357
358.. code-block:: bash
359
360 $ c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`
361
362In general, it is advisable to include several additional build parameters
363that can considerably reduce the size of the created binary. Refer to section
364:ref:`cmake` for a detailed example of a suitable cross-platform CMake-based
365build system that works on all platforms including Windows.
366
367.. note::
368
369 On Linux and macOS, it's better to (intentionally) not link against
370 ``libpython``. The symbols will be resolved when the extension library
371 is loaded into a Python binary. This is preferable because you might
372 have several different installations of a given Python version (e.g. the
373 system-provided Python, and one that ships with a piece of commercial
374 software). In this way, the plugin will work with both versions, instead
375 of possibly importing a second Python library into a process that already
376 contains one (which will lead to a segfault).
Dean Moldovan6d2411f2017-04-22 23:24:13 +0200377
Wenzel Jakobf3de2d52016-12-26 13:34:28 +0100378Generating binding code automatically
379=====================================
380
381The ``Binder`` project is a tool for automatic generation of pybind11 binding
382code by introspecting existing C++ codebases using LLVM/Clang. See the
383[binder]_ documentation for details.
384
385.. [binder] http://cppbinder.readthedocs.io/en/latest/about.html
Dustin Spicuzza2c4cd842019-11-24 02:36:48 -0500386
387[AutoWIG]_ is a Python library that wraps automatically compiled libraries into
388high-level languages. It parses C++ code using LLVM/Clang technologies and
389generates the wrappers using the Mako templating engine. The approach is automatic,
390extensible, and applies to very complex C++ libraries, composed of thousands of
391classes or incorporating modern meta-programming constructs.
392
393.. [AutoWIG] https://github.com/StatisKit/AutoWIG
Dustin Spicuzza6f3470f2020-08-10 16:10:45 -0400394
395[robotpy-build]_ is a is a pure python, cross platform build tool that aims to
396simplify creation of python wheels for pybind11 projects, and provide
397cross-project dependency management. Additionally, it is able to autogenerate
398customizable pybind11-based wrappers by parsing C++ header files.
399
400.. [robotpy-build] https://robotpy-build.readthedocs.io