blob: bfb1cd8056ee632958fb5759b96e170b4c5be12f [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
Dean Moldovan24ddf4b2016-05-27 00:11:52 +020036 cmake_minimum_required(VERSION 2.8.12)
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020037 project(example)
38
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
Dean Moldovan0cbec5c2016-12-16 22:58:37 +010053pybind11_add_module
54-------------------
Lori A. Burns5cafc992016-12-13 10:55:38 -050055
Dean Moldovan0cbec5c2016-12-16 22:58:37 +010056To ease the creation of Python extension modules, pybind11 provides a CMake
57function with the following signature:
58
59.. code-block:: cmake
60
61 pybind11_add_module(<name> [MODULE | SHARED] [EXCLUDE_FROM_ALL]
Axel Huebl435dbdd2018-08-29 13:20:11 +020062 [NO_EXTRAS] [SYSTEM] [THIN_LTO] source1 [source2 ...])
Dean Moldovan0cbec5c2016-12-16 22:58:37 +010063
64This function behaves very much like CMake's builtin ``add_library`` (in fact,
65it's a wrapper function around that command). It will add a library target
66called ``<name>`` to be built from the listed source files. In addition, it
67will take care of all the Python-specific compiler and linker flags as well
68as the OS- and Python-version-specific file extension. The produced target
69``<name>`` can be further manipulated with regular CMake commands.
70
71``MODULE`` or ``SHARED`` may be given to specify the type of library. If no
72type is given, ``MODULE`` is used by default which ensures the creation of a
73Python-exclusive module. Specifying ``SHARED`` will create a more traditional
74dynamic library which can also be linked from elsewhere. ``EXCLUDE_FROM_ALL``
75removes this target from the default build (see CMake docs for details).
76
77Since pybind11 is a template library, ``pybind11_add_module`` adds compiler
78flags to ensure high quality code generation without bloat arising from long
Jason Rhinelander97aa54f2017-08-10 12:08:42 -040079symbol names and duplication of code in different translation units. It
80sets default visibility to *hidden*, which is required for some pybind11
81features and functionality when attempting to load multiple pybind11 modules
82compiled under different pybind11 versions. It also adds additional flags
83enabling LTO (Link Time Optimization) and strip unneeded symbols. See the
84:ref:`FAQ entry <faq:symhidden>` for a more detailed explanation. These
85latter optimizations are never applied in ``Debug`` mode. If ``NO_EXTRAS`` is
86given, they will always be disabled, even in ``Release`` mode. However, this
87will result in code bloat and is generally not recommended.
Dean Moldovan0cbec5c2016-12-16 22:58:37 +010088
Axel Huebl435dbdd2018-08-29 13:20:11 +020089By default, pybind11 and Python headers will be included with ``-I``. In order
90to include pybind11 as system library, e.g. to avoid warnings in downstream
91code with warn-levels outside of pybind11's scope, set the option ``SYSTEM``.
92
Dean Moldovan0cbec5c2016-12-16 22:58:37 +010093As stated above, LTO is enabled by default. Some newer compilers also support
94different flavors of LTO such as `ThinLTO`_. Setting ``THIN_LTO`` will cause
95the function to prefer this flavor if available. The function falls back to
96regular LTO if ``-flto=thin`` is not available.
97
98.. _ThinLTO: http://clang.llvm.org/docs/ThinLTO.html
99
100Configuration variables
101-----------------------
102
Jason Rhinelander77710ff2017-05-09 14:37:48 -0400103By default, pybind11 will compile modules with the C++14 standard, if available
104on the target compiler, falling back to C++11 if C++14 support is not
105available. Note, however, that this default is subject to change: future
106pybind11 releases are expected to migrate to newer C++ standards as they become
107available. To override this, the standard flag can be given explicitly in
Axel Huebl6ebfc4b2020-04-25 18:10:53 -0700108`CMAKE_CXX_STANDARD <https://cmake.org/cmake/help/v3.17/variable/CMAKE_CXX_STANDARD.html>`_:
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100109
110.. code-block:: cmake
111
Jason Rhinelander77710ff2017-05-09 14:37:48 -0400112 # Use just one of these:
Axel Huebl6ebfc4b2020-04-25 18:10:53 -0700113 set(CMAKE_CXX_STANDARD 11)
114 set(CMAKE_CXX_STANDARD 14)
115 set(CMAKE_CXX_STANDARD 17) # Experimental C++17 support
Jason Rhinelander77710ff2017-05-09 14:37:48 -0400116
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100117 add_subdirectory(pybind11) # or find_package(pybind11)
118
119Note that this and all other configuration variables must be set **before** the
Jason Rhinelander77710ff2017-05-09 14:37:48 -0400120call to ``add_subdirectory`` or ``find_package``. The variables can also be set
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100121when calling CMake from the command line using the ``-D<variable>=<value>`` flag.
122
123The target Python version can be selected by setting ``PYBIND11_PYTHON_VERSION``
124or an exact Python installation can be specified with ``PYTHON_EXECUTABLE``.
125For example:
126
127.. code-block:: bash
128
129 cmake -DPYBIND11_PYTHON_VERSION=3.6 ..
130 # or
131 cmake -DPYTHON_EXECUTABLE=path/to/python ..
132
133find_package vs. add_subdirectory
134---------------------------------
135
136For CMake-based projects that don't include the pybind11 repository internally,
137an external installation can be detected through ``find_package(pybind11)``.
138See the `Config file`_ docstring for details of relevant CMake variables.
Lori A. Burns5cafc992016-12-13 10:55:38 -0500139
140.. code-block:: cmake
141
142 cmake_minimum_required(VERSION 2.8.12)
143 project(example)
144
145 find_package(pybind11 REQUIRED)
146 pybind11_add_module(example example.cpp)
147
nstelzenc2514342019-06-10 16:35:36 +0200148Note that ``find_package(pybind11)`` will only work correctly if pybind11
149has been correctly installed on the system, e. g. after downloading or cloning
150the pybind11 repository :
151
152.. code-block:: bash
153
154 cd pybind11
155 mkdir build
156 cd build
157 cmake ..
158 make install
159
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100160Once detected, the aforementioned ``pybind11_add_module`` can be employed as
161before. The function usage and configuration variables are identical no matter
162if pybind11 is added as a subdirectory or found as an installed package. You
163can refer to the same [cmake_example]_ repository for a full sample project
164-- just swap out ``add_subdirectory`` for ``find_package``.
Lori A. Burns5cafc992016-12-13 10:55:38 -0500165
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100166.. _Config file: https://github.com/pybind/pybind11/blob/master/tools/pybind11Config.cmake.in
167
168Advanced: interface library target
169----------------------------------
170
171When using a version of CMake greater than 3.0, pybind11 can additionally
Dean Moldovan71e8a792016-12-17 21:38:57 +0100172be used as a special *interface library* . The target ``pybind11::module``
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100173is available with pybind11 headers, Python headers and libraries as needed,
174and C++ compile definitions attached. This target is suitable for linking
175to an independently constructed (through ``add_library``, not
176``pybind11_add_module``) target in the consuming project.
Lori A. Burns5cafc992016-12-13 10:55:38 -0500177
178.. code-block:: cmake
179
180 cmake_minimum_required(VERSION 3.0)
181 project(example)
182
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100183 find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11)
Lori A. Burns5cafc992016-12-13 10:55:38 -0500184
Dean Moldovan0cbec5c2016-12-16 22:58:37 +0100185 add_library(example MODULE main.cpp)
Dean Moldovan71e8a792016-12-17 21:38:57 +0100186 target_link_libraries(example PRIVATE pybind11::module)
Lori A. Burns5cafc992016-12-13 10:55:38 -0500187 set_target_properties(example PROPERTIES PREFIX "${PYTHON_MODULE_PREFIX}"
188 SUFFIX "${PYTHON_MODULE_EXTENSION}")
189
190.. warning::
191
192 Since pybind11 is a metatemplate library, it is crucial that certain
193 compiler flags are provided to ensure high quality code generation. In
194 contrast to the ``pybind11_add_module()`` command, the CMake interface
195 library only provides the *minimal* set of parameters to ensure that the
196 code using pybind11 compiles, but it does **not** pass these extra compiler
197 flags (i.e. this is up to you).
198
199 These include Link Time Optimization (``-flto`` on GCC/Clang/ICPC, ``/GL``
Jason Rhinelander97aa54f2017-08-10 12:08:42 -0400200 and ``/LTCG`` on Visual Studio) and .OBJ files with many sections on Visual
201 Studio (``/bigobj``). The :ref:`FAQ <faq:symhidden>` contains an
Lori A. Burns5cafc992016-12-13 10:55:38 -0500202 explanation on why these are needed.
Wenzel Jakobf3de2d52016-12-26 13:34:28 +0100203
Dean Moldovan6d2411f2017-04-22 23:24:13 +0200204Embedding the Python interpreter
205--------------------------------
206
207In addition to extension modules, pybind11 also supports embedding Python into
208a C++ executable or library. In CMake, simply link with the ``pybind11::embed``
209target. It provides everything needed to get the interpreter running. The Python
210headers and libraries are attached to the target. Unlike ``pybind11::module``,
211there is no need to manually set any additional properties here. For more
212information about usage in C++, see :doc:`/advanced/embedding`.
213
214.. code-block:: cmake
215
216 cmake_minimum_required(VERSION 3.0)
217 project(example)
218
219 find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11)
220
Dean Moldovan8f6c1292017-05-31 13:48:39 +0200221 add_executable(example main.cpp)
Dean Moldovan6d2411f2017-04-22 23:24:13 +0200222 target_link_libraries(example PRIVATE pybind11::embed)
223
Ivan Smirnov5cbfda52017-08-30 20:58:43 +0100224.. _building_manually:
225
226Building manually
227=================
228
229pybind11 is a header-only library, hence it is not necessary to link against
230any special libraries and there are no intermediate (magic) translation steps.
231
232On Linux, you can compile an example such as the one given in
233:ref:`simple_example` using the following command:
234
235.. code-block:: bash
236
237 $ c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`
238
239The flags given here assume that you're using Python 3. For Python 2, just
240change the executable appropriately (to ``python`` or ``python2``).
241
242The ``python3 -m pybind11 --includes`` command fetches the include paths for
243both pybind11 and Python headers. This assumes that pybind11 has been installed
244using ``pip`` or ``conda``. If it hasn't, you can also manually specify
245``-I <path-to-pybind11>/include`` together with the Python includes path
246``python3-config --includes``.
247
248Note that Python 2.7 modules don't use a special suffix, so you should simply
249use ``example.so`` instead of ``example`python3-config --extension-suffix```.
250Besides, the ``--extension-suffix`` option may or may not be available, depending
251on the distribution; in the latter case, the module extension can be manually
252set to ``.so``.
253
254On Mac OS: the build command is almost the same but it also requires passing
255the ``-undefined dynamic_lookup`` flag so as to ignore missing symbols when
256building the module:
257
258.. code-block:: bash
259
260 $ c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`
261
262In general, it is advisable to include several additional build parameters
263that can considerably reduce the size of the created binary. Refer to section
264:ref:`cmake` for a detailed example of a suitable cross-platform CMake-based
265build system that works on all platforms including Windows.
266
267.. note::
268
269 On Linux and macOS, it's better to (intentionally) not link against
270 ``libpython``. The symbols will be resolved when the extension library
271 is loaded into a Python binary. This is preferable because you might
272 have several different installations of a given Python version (e.g. the
273 system-provided Python, and one that ships with a piece of commercial
274 software). In this way, the plugin will work with both versions, instead
275 of possibly importing a second Python library into a process that already
276 contains one (which will lead to a segfault).
Dean Moldovan6d2411f2017-04-22 23:24:13 +0200277
Wenzel Jakobf3de2d52016-12-26 13:34:28 +0100278Generating binding code automatically
279=====================================
280
281The ``Binder`` project is a tool for automatic generation of pybind11 binding
282code by introspecting existing C++ codebases using LLVM/Clang. See the
283[binder]_ documentation for details.
284
285.. [binder] http://cppbinder.readthedocs.io/en/latest/about.html
Dustin Spicuzza2c4cd842019-11-24 02:36:48 -0500286
287[AutoWIG]_ is a Python library that wraps automatically compiled libraries into
288high-level languages. It parses C++ code using LLVM/Clang technologies and
289generates the wrappers using the Mako templating engine. The approach is automatic,
290extensible, and applies to very complex C++ libraries, composed of thousands of
291classes or incorporating modern meta-programming constructs.
292
293.. [AutoWIG] https://github.com/StatisKit/AutoWIG