1.. _compiling:
2
3Build 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
12the [python_example]_ repository.
13
14.. [python_example] https://github.com/pybind/python_example
15
16Building with cppimport
17========================
18
19[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.
23
24.. [cppimport] https://github.com/tbenthompson/cppimport
25
26.. _cmake:
27
28Building with CMake
29===================
30
31For C++ codebases that have an existing CMake-based build system, a Python
32extension module can be created with just a few lines of code:
33
34.. code-block:: cmake
35
36    cmake_minimum_required(VERSION 2.8.12)
37    project(example)
38
39    add_subdirectory(pybind11)
40    pybind11_add_module(example example.cpp)
41
42This assumes that the pybind11 repository is located in a subdirectory named
43:file:`pybind11` and that the code is located in a file named :file:`example.cpp`.
44The 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.
47
48A working sample project, including a way to invoke CMake from :file:`setup.py` for
49PyPI integration, can be found in the [cmake_example]_  repository.
50
51.. [cmake_example] https://github.com/pybind/cmake_example
52
53pybind11_add_module
54-------------------
55
56To 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]
62                        [NO_EXTRAS] [SYSTEM] [THIN_LTO] source1 [source2 ...])
63
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
79symbol 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.
88
89By 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
93As 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
103By 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
108``PYBIND11_CPP_STANDARD``:
109
110.. code-block:: cmake
111
112    # Use just one of these:
113    # GCC/clang:
114    set(PYBIND11_CPP_STANDARD -std=c++11)
115    set(PYBIND11_CPP_STANDARD -std=c++14)
116    set(PYBIND11_CPP_STANDARD -std=c++1z) # Experimental C++17 support
117    # MSVC:
118    set(PYBIND11_CPP_STANDARD /std:c++14)
119    set(PYBIND11_CPP_STANDARD /std:c++latest) # Enables some MSVC C++17 features
120
121    add_subdirectory(pybind11)  # or find_package(pybind11)
122
123Note that this and all other configuration variables must be set **before** the
124call to ``add_subdirectory`` or ``find_package``. The variables can also be set
125when calling CMake from the command line using the ``-D<variable>=<value>`` flag.
126
127The target Python version can be selected by setting ``PYBIND11_PYTHON_VERSION``
128or an exact Python installation can be specified with ``PYTHON_EXECUTABLE``.
129For example:
130
131.. code-block:: bash
132
133    cmake -DPYBIND11_PYTHON_VERSION=3.6 ..
134    # or
135    cmake -DPYTHON_EXECUTABLE=path/to/python ..
136
137find_package vs. add_subdirectory
138---------------------------------
139
140For CMake-based projects that don't include the pybind11 repository internally,
141an external installation can be detected through ``find_package(pybind11)``.
142See the `Config file`_ docstring for details of relevant CMake variables.
143
144.. code-block:: cmake
145
146    cmake_minimum_required(VERSION 2.8.12)
147    project(example)
148
149    find_package(pybind11 REQUIRED)
150    pybind11_add_module(example example.cpp)
151
152Note that ``find_package(pybind11)`` will only work correctly if pybind11
153has been correctly installed on the system, e. g. after downloading or cloning
154the pybind11 repository  :
155
156.. code-block:: bash
157
158    cd pybind11
159    mkdir build
160    cd build
161    cmake ..
162    make install
163
164Once detected, the aforementioned ``pybind11_add_module`` can be employed as
165before. The function usage and configuration variables are identical no matter
166if pybind11 is added as a subdirectory or found as an installed package. You
167can refer to the same [cmake_example]_ repository for a full sample project
168-- just swap out ``add_subdirectory`` for ``find_package``.
169
170.. _Config file: https://github.com/pybind/pybind11/blob/master/tools/pybind11Config.cmake.in
171
172Advanced: interface library target
173----------------------------------
174
175When using a version of CMake greater than 3.0, pybind11 can additionally
176be used as a special *interface library* . The target ``pybind11::module``
177is available with pybind11 headers, Python headers and libraries as needed,
178and C++ compile definitions attached. This target is suitable for linking
179to an independently constructed (through ``add_library``, not
180``pybind11_add_module``) target in the consuming project.
181
182.. code-block:: cmake
183
184    cmake_minimum_required(VERSION 3.0)
185    project(example)
186
187    find_package(pybind11 REQUIRED)  # or add_subdirectory(pybind11)
188
189    add_library(example MODULE main.cpp)
190    target_link_libraries(example PRIVATE pybind11::module)
191    set_target_properties(example PROPERTIES PREFIX "${PYTHON_MODULE_PREFIX}"
192                                             SUFFIX "${PYTHON_MODULE_EXTENSION}")
193
194.. warning::
195
196    Since pybind11 is a metatemplate library, it is crucial that certain
197    compiler flags are provided to ensure high quality code generation. In
198    contrast to the ``pybind11_add_module()`` command, the CMake interface
199    library only provides the *minimal* set of parameters to ensure that the
200    code using pybind11 compiles, but it does **not** pass these extra compiler
201    flags (i.e. this is up to you).
202
203    These include Link Time Optimization (``-flto`` on GCC/Clang/ICPC, ``/GL``
204    and ``/LTCG`` on Visual Studio) and .OBJ files with many sections on Visual
205    Studio (``/bigobj``).  The :ref:`FAQ <faq:symhidden>` contains an
206    explanation on why these are needed.
207
208Embedding the Python interpreter
209--------------------------------
210
211In addition to extension modules, pybind11 also supports embedding Python into
212a C++ executable or library. In CMake, simply link with the ``pybind11::embed``
213target. It provides everything needed to get the interpreter running. The Python
214headers and libraries are attached to the target. Unlike ``pybind11::module``,
215there is no need to manually set any additional properties here. For more
216information about usage in C++, see :doc:`/advanced/embedding`.
217
218.. code-block:: cmake
219
220    cmake_minimum_required(VERSION 3.0)
221    project(example)
222
223    find_package(pybind11 REQUIRED)  # or add_subdirectory(pybind11)
224
225    add_executable(example main.cpp)
226    target_link_libraries(example PRIVATE pybind11::embed)
227
228.. _building_manually:
229
230Building manually
231=================
232
233pybind11 is a header-only library, hence it is not necessary to link against
234any special libraries and there are no intermediate (magic) translation steps.
235
236On Linux, you can compile an example such as the one given in
237:ref:`simple_example` using the following command:
238
239.. code-block:: bash
240
241    $ c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`
242
243The flags given here assume that you're using Python 3. For Python 2, just
244change the executable appropriately (to ``python`` or ``python2``).
245
246The ``python3 -m pybind11 --includes`` command fetches the include paths for
247both pybind11 and Python headers. This assumes that pybind11 has been installed
248using ``pip`` or ``conda``. If it hasn't, you can also manually specify
249``-I <path-to-pybind11>/include`` together with the Python includes path
250``python3-config --includes``.
251
252Note that Python 2.7 modules don't use a special suffix, so you should simply
253use ``example.so`` instead of ``example`python3-config --extension-suffix```.
254Besides, the ``--extension-suffix`` option may or may not be available, depending
255on the distribution; in the latter case, the module extension can be manually
256set to ``.so``.
257
258On Mac OS: the build command is almost the same but it also requires passing
259the ``-undefined dynamic_lookup`` flag so as to ignore missing symbols when
260building the module:
261
262.. code-block:: bash
263
264    $ c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`
265
266In general, it is advisable to include several additional build parameters
267that can considerably reduce the size of the created binary. Refer to section
268:ref:`cmake` for a detailed example of a suitable cross-platform CMake-based
269build system that works on all platforms including Windows.
270
271.. note::
272
273    On Linux and macOS, it's better to (intentionally) not link against
274    ``libpython``. The symbols will be resolved when the extension library
275    is loaded into a Python binary. This is preferable because you might
276    have several different installations of a given Python version (e.g. the
277    system-provided Python, and one that ships with a piece of commercial
278    software). In this way, the plugin will work with both versions, instead
279    of possibly importing a second Python library into a process that already
280    contains one (which will lead to a segfault).
281
282Generating binding code automatically
283=====================================
284
285The ``Binder`` project is a tool for automatic generation of pybind11 binding
286code by introspecting existing C++ codebases using LLVM/Clang. See the
287[binder]_ documentation for details.
288
289.. [binder] http://cppbinder.readthedocs.io/en/latest/about.html
290