Skip to content

Commit c18cd70

Browse files
itamaroclaude
andcommitted
[3.14] gh-104612: Document linking embedders for several Python versions (GH-162498)
Add a section to the embedding guide that explains, for Linux, that linking with `pythonX.Y-config --ldflags --embed` ties an application to one minor version even when it only uses the Limited API, and how a single binary can instead load `libpython3.so` at run time. Mention renaming the dependency with `patchelf` as a packaging workaround, and list the limitations of both approaches. Related discussion: https://discuss.python.org/t/on-embedders-and-stable-abi/110197 (cherry picked from commit cb9d78f) Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1 parent c074696 commit c18cd70

2 files changed

Lines changed: 179 additions & 0 deletions

File tree

‎Doc/c-api/stable.rst‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,8 @@ Stable Application Binary Interface
5959
For simplicity, this document talks about *extensions*, but the Limited API
6060
and Stable ABI work the same way for all uses of the API – for example,
6161
embedding Python.
62+
When embedding Python on Linux, see :ref:`embedding-python-versions`
63+
for how to link the application and for limitations.
6264

6365
.. _limited-c-api:
6466

@@ -149,6 +151,8 @@ distributed where a version-specific one is not available – for example,
149151
for prereleases of an upcoming Python version.
150152

151153

154+
.. _limited-api-caveats:
155+
152156
Limited API Caveats
153157
-------------------
154158

‎Doc/extending/embedding.rst‎

Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,3 +356,178 @@ combine together. For example:
356356
357357
358358
.. XXX similar documentation for Windows missing
359+
360+
361+
.. _embedding-python-versions:
362+
363+
Linking for one or several Python versions on Linux
364+
===================================================
365+
366+
The flags obtained from ``pythonX.Y-config --ldflags --embed`` link the
367+
application against one minor version of Python.
368+
If that Python was built as a shared library, the executable records a
369+
dependency on the versioned library, such as :file:`libpython3.12.so.1.0`,
370+
and expected that specific minor version at runtime.
371+
This is the recommended setup for most host (embedding) applications.
372+
Build the application for each Python version that it supports,
373+
or distribute it together with the Python that it was built with.
374+
375+
Using the :ref:`Limited API <limited-c-api>` does not change this.
376+
Defining :c:macro:`Py_LIMITED_API` restricts your source code to API that is
377+
compatible across minor versions, but the library dependency is recorded when
378+
linking, so the executable still requires :file:`libpython3.12.so.1.0`.
379+
380+
A binary that needs to run with several minor Python versions must use only
381+
the Limited API and must *also* avoid the versioned dependency.
382+
383+
.. warning::
384+
385+
Host applications that use the :ref:`Limited API <limited-c-api>`
386+
must be aware of the following limitations:
387+
388+
* It can only initialize Python with :c:func:`Py_Initialize` or
389+
:c:func:`Py_InitializeEx`, which set Python up much like the
390+
:program:`python` command does.
391+
They honor :envvar:`PYTHONHOME` and :envvar:`PYTHONPATH`, add the
392+
:data:`user site-packages directory <site.USER_SITE>` to
393+
:data:`sys.path`, and terminate the process if initialization fails.
394+
They set :data:`sys.executable` to the :program:`python3` program found
395+
on :envvar:`!PATH`, which can belong to a different Python installation
396+
than the library that was loaded.
397+
The functions that accept an
398+
:ref:`isolated configuration <init-isolated-conf>`,
399+
:c:func:`Py_InitializeFromConfig` and
400+
:c:func:`Py_InitializeFromInitConfig`, are not part of the Limited API.
401+
* The Python that gets loaded is only known at run-time.
402+
Checking that it is suitable is up to the application.
403+
An incompatible Python, such as a too-old or too-new version,
404+
is not rejected automatically.
405+
* The Stable ABI keeps functions available in later versions, but it does
406+
not guarantee identical behavior.
407+
The default configuration and the way :data:`sys.path` is computed can
408+
change between Python versions, and between installations of the same
409+
version.
410+
Test the application with every Python version and installation that it
411+
is meant to support.
412+
See also :ref:`limited-api-caveats`.
413+
414+
A Python built with :option:`--enable-shared` and without
415+
:option:`--with-pydebug` installs :file:`libpython3.so` next to the versioned
416+
library.
417+
When the dynamic loader loads this library, it also loads the versioned
418+
library that it was built with, and symbols looked up through
419+
:file:`libpython3.so` are found in the versioned library.
420+
An application can therefore load :file:`libpython3.so` with
421+
:manpage:`dlopen(3)` and look up each function that it uses with
422+
:manpage:`dlsym(3)`.
423+
424+
This only works at run time.
425+
When linking an executable, the linker does not use the dependencies of a
426+
library to resolve symbols, and :file:`libpython3.so` defines no Python
427+
symbols of its own, so linking with ``-lpython3`` fails with
428+
``undefined reference`` errors.
429+
430+
For example, with Python 3.12 as the oldest supported version::
431+
432+
#define Py_LIMITED_API 0x030c0000 /* Limited API 3.12 */
433+
#include <Python.h>
434+
#include <dlfcn.h>
435+
#include <stdio.h>
436+
437+
/* The API this application uses, declared as in Python.h.
438+
Everything is reached through these pointers. */
439+
static struct {
440+
const unsigned long *Version;
441+
const char *(*GetVersion)(void);
442+
void (*InitializeEx)(int);
443+
int (*FinalizeEx)(void);
444+
} py;
445+
446+
#define LOAD(lib, pointer, name) \
447+
((*(void **)&(pointer) = dlsym(lib, name)) != NULL)
448+
449+
int
450+
main(int argc, char *argv[])
451+
{
452+
/* For brevity, the path comes from the command line. A real
453+
application reads it from its own configuration. */
454+
if (argc != 2 || argv[1][0] != '/') {
455+
fprintf(stderr, "usage: %s /absolute/path/to/libpython3.so\n",
456+
argv[0]);
457+
return 2;
458+
}
459+
/* RTLD_GLOBAL is required: it lets the extension modules that
460+
Python imports find Python's symbols. */
461+
void *lib = dlopen(argv[1], RTLD_NOW | RTLD_GLOBAL);
462+
if (lib == NULL) {
463+
fprintf(stderr, "Python is not available: %s\n", dlerror());
464+
return 1;
465+
}
466+
if (!LOAD(lib, py.Version, "Py_Version")
467+
|| !LOAD(lib, py.GetVersion, "Py_GetVersion")
468+
|| !LOAD(lib, py.InitializeEx, "Py_InitializeEx")
469+
|| !LOAD(lib, py.FinalizeEx, "Py_FinalizeEx"))
470+
{
471+
fprintf(stderr, "Unsupported Python: %s\n", dlerror());
472+
return 1;
473+
}
474+
if (*py.Version < Py_LIMITED_API) {
475+
fprintf(stderr, "Python %s is older than 3.12\n", py.GetVersion());
476+
return 1;
477+
}
478+
479+
py.InitializeEx(0);
480+
printf("Loaded Python %s\n", py.GetVersion());
481+
return py.FinalizeEx() < 0 ? 120 : 0;
482+
}
483+
484+
Compile the program with Python's headers, but without the output of
485+
``--ldflags``:
486+
487+
.. code-block:: shell-session
488+
489+
$ gcc $(/opt/bin/python3.12-config --includes) -o myapp myapp.c
490+
$ ./myapp /usr/local/lib/libpython3.so
491+
Loaded Python 3.14.10 (main, Nov 5 2026, 09:47:10) [GCC 14.2.0]
492+
493+
No Python library is passed to the linker, so the executable does not depend
494+
on one.
495+
You can check this with ``readelf``:
496+
497+
.. code-block:: shell-session
498+
499+
$ readelf -d myapp | grep NEEDED
500+
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
501+
502+
For the same reason, Python functions can only be called through such
503+
pointers.
504+
This includes the functions that macros in :file:`Python.h` expand to:
505+
for example, call :c:func:`Py_DecRef` through a pointer instead of using
506+
:c:func:`Py_DECREF`.
507+
508+
* The path passed to ``dlopen()`` selects the code that runs in your process.
509+
It should come from a trusted source and name a file that only trusted
510+
users can replace.
511+
* Use an absolute path.
512+
The dynamic loader looks for a name without a slash in its usual search
513+
path, such as :envvar:`!LD_LIBRARY_PATH` and the system library directories.
514+
It looks for the versioned library that :file:`libpython3.so` depends on in
515+
the same way, and not next to :file:`libpython3.so`.
516+
To choose the exact file, pass the absolute path of the versioned library
517+
to ``dlopen()`` instead.
518+
* ``RTLD_GLOBAL`` is required.
519+
Extension modules are generally not linked against a Python library,
520+
so Python can only import them if its symbols are visible globally.
521+
522+
.. rubric:: Unsupported workaround: renaming the dependency after linking
523+
524+
Some applications are instead linked against a versioned library as described
525+
:ref:`above <compiling>`, and the dependency recorded in the executable is
526+
then renamed to :file:`libpython3.so`, for example with ``patchelf``.
527+
528+
.. warning::
529+
530+
Renaming the dependency this way is unsupported.
531+
Nothing checks that such an executable only uses the Stable ABI, and it
532+
can contain copies of Python data, such as ``PyLong_Type``, whose size
533+
differs between Python versions.

0 commit comments

Comments
 (0)