From ac5ab8c8b69ef1c03c2936fc5b6c79001419e4de Mon Sep 17 00:00:00 2001 From: Itamar Oren Date: Mon, 23 Nov 2026 11:41:56 -0800 Subject: [PATCH 1/4] gh-104612: Document linking embedders for several Python versions 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 --- Doc/c-api/stable.rst | 2 + Doc/extending/embedding.rst | 176 ++++++++++++++++++++++++++++++++++++ 2 files changed, 178 insertions(+) diff --git a/Doc/c-api/stable.rst b/Doc/c-api/stable.rst index 13e5d5c96135c0e..b0fc89db2caff8f 100644 --- a/Doc/c-api/stable.rst +++ b/Doc/c-api/stable.rst @@ -64,6 +64,8 @@ versions of Python, without recompilation. For simplicity, this document talks about *extensions*, but Stable ABI works the same way for all uses of the API – for example, embedding Python. + When embedding Python on Linux, see :ref:`embedding-python-versions` + for how to link the application and for limitations. There are two Stable ABIs: diff --git a/Doc/extending/embedding.rst b/Doc/extending/embedding.rst index 8a87d7cb1c3b4ca..a7604de6604258c 100644 --- a/Doc/extending/embedding.rst +++ b/Doc/extending/embedding.rst @@ -356,3 +356,179 @@ combine together. For example: .. XXX similar documentation for Windows missing + + +.. _embedding-python-versions: + +Linking for one or several Python versions on Linux +=================================================== + +The flags obtained from ``pythonX.Y-config --ldflags --embed`` link the +application against one minor version of Python. +If that Python was built as a shared library, the executable records a +dependency on the versioned library, such as :file:`libpython3.12.so.1.0`, +and expected that specific minor version at runtime. +This is the recommended setup for most host (embedding) applications. +Build the application for each Python version that it supports, +or distribute it together with the Python that it was built with. + +Using the :ref:`Limited API ` does not change this. +Defining :c:macro:`Py_LIMITED_API` restricts your source code to API that is +compatible across minor versions, but the library dependency is recorded when +linking, so the executable still requires :file:`libpython3.12.so.1.0`. + +A binary that needs to run with several minor Python versions must use only +the Limited API and must *also* avoid the versioned dependency. + +.. warning:: + + Host application that uses the :ref:`Limited API ` + must be aware of the following limitations: + + * It can only initialize Python with :c:func:`Py_Initialize` or + :c:func:`Py_InitializeEx`, which set Python up much like the + :program:`python` command does. + They honor :envvar:`PYTHONHOME` and :envvar:`PYTHONPATH`, add the + :data:`user site-packages directory ` to + :data:`sys.path`, and terminate the process if initialization fails. + They set :data:`sys.executable` to the :program:`python3` program found + on :envvar:`!PATH`, which can belong to a different Python installation + than the library that was loaded. + The functions that accept an + :ref:`isolated configuration `, + :c:func:`Py_InitializeFromConfig` and + :c:func:`Py_InitializeFromInitConfig`, are not part of the Limited API. + * The Python that gets loaded is only known at run-time. + Checking that it is suitable is up to the application. + An incompatible Python, such as a too-old or too-new version, + is not rejected automatically. + * The Stable ABI keeps functions available in later versions, but it does + not guarantee identical behavior. + The default configuration and the way :data:`sys.path` is computed can + change between Python versions, and between installations of the same + version. + Test the application with every Python version and installation that it + is meant to support. + See also :ref:`limited-api-caveats`. + +A Python built with :option:`--enable-shared` and without +:option:`--with-pydebug` installs :file:`libpython3.so` next to the versioned +library. +This library defines no Python symbols itself. +It only depends on the versioned library, which the dynamic loader loads +along with it. +Linking an executable with ``-lpython3`` therefore fails with +``undefined reference`` errors, but an application can load +:file:`libpython3.so` with :manpage:`dlopen(3)` and look up each function that +it uses with :manpage:`dlsym(3)`. + +For example, with Python 3.12 as the oldest supported version:: + + #define Py_LIMITED_API 0x030c0000 /* Limited API 3.12 */ + #include + #include + #include + + /* The API this application uses, declared as in Python.h. + Everything is reached through these pointers. */ + static struct { + const unsigned long *Version; /* Py_Version */ + const char *(*GetVersion)(void); /* Py_GetVersion */ + void (*InitializeEx)(int); /* Py_InitializeEx */ + int (*FinalizeEx)(void); /* Py_FinalizeEx */ + } py; + + #define LOAD(lib, name) \ + ((*(void **)&py.name = dlsym(lib, "Py_" #name)) != NULL) + + int + main(int argc, char *argv[]) + { + /* For brevity, the path comes from the command line. A real + application reads it from its own configuration. */ + if (argc != 2 || argv[1][0] != '/') { + fprintf(stderr, "usage: %s /absolute/path/to/libpython3.so\n", + argv[0]); + return 2; + } + void *lib = dlopen(argv[1], RTLD_NOW | RTLD_GLOBAL); + if (lib == NULL) { + fprintf(stderr, "Python is not available: %s\n", dlerror()); + return 1; + } + if (!LOAD(lib, Version) || !LOAD(lib, GetVersion) + || !LOAD(lib, InitializeEx) || !LOAD(lib, FinalizeEx)) + { + fprintf(stderr, "Unsupported Python: %s\n", dlerror()); + return 1; + } + if (*py.Version < Py_LIMITED_API) { + fprintf(stderr, "Python %s is older than 3.12\n", py.GetVersion()); + return 1; + } + + py.InitializeEx(0); + printf("Loaded Python %s\n", py.GetVersion()); + return py.FinalizeEx() < 0 ? 120 : 0; + } + +Compile the program with Python's headers, but without the output of +``--ldflags``. + +.. code-block:: shell-session + + $ gcc $(/opt/bin/python3.12-config --includes) -o myapp myapp.c + $ readelf -d myapp | grep NEEDED + 0x0000000000000001 (NEEDED) Shared library: [libc.so.6] + $ ./myapp /usr/local/lib/libpython3.so + Loaded Python 3.14.10 (main, Nov 5 2026, 09:47:10) [GCC 14.2.0] + +No Python library is passed to the linker, so the executable does not depend +on one. +For the same reason, Python functions can only be called through such +pointers. +This includes the functions that macros in :file:`Python.h` expand to: +for example, call :c:func:`Py_DecRef` through a pointer instead of using +:c:func:`Py_DECREF`. + +* The path passed to ``dlopen()`` selects the code that runs in your process. + Use an absolute path that comes from a trusted source and that names a file + only trusted users can replace. +* The dynamic loader looks for the versioned library by name in its usual + search path, such as :envvar:`!LD_LIBRARY_PATH` and the system library + directories, and not next to :file:`libpython3.so`. + To choose the exact file, pass the absolute path of the versioned library + to ``dlopen()`` instead. +* ``RTLD_GLOBAL`` makes Python's symbols available to the extension modules + that Python imports, which are normally not linked against a Python library. + +An existing application that calls the C API directly can instead be linked +as described :ref:`above `, and have the dependency recorded in +the executable renamed afterwards, for example with +`patchelf `__: + +.. code-block:: shell-session + + $ patchelf --replace-needed libpython3.12.so.1.0 libpython3.so myapp + +.. warning:: + + This is a packaging workaround. + It does not make the application compatible with other Python versions, + and it has additional limitations and caveats: + + * Renaming the dependency does not check that the application uses only + the Stable ABI. + Compile it with :c:macro:`Py_LIMITED_API` defined, as described in + :ref:`abi3-compiling`. + * If the application refers to a Python data symbol directly, for example + ``&PyLong_Type``, the linker may have used a copy relocation. + This reserves space for the object in the executable, using its size in + the Python version that the application was linked against. + That size is not part of the Stable ABI and can differ between versions. + Look for such relocations with ``readelf -rW myapp | grep COPY``, and + compile the application as position-independent code (``-fPIC``) to + avoid them. + * The dynamic loader must find :file:`libpython3.so` in its search path + when the application starts. + Otherwise the application does not start at all. From 02e140937e95df133cffecc04426522f23c7bb1f Mon Sep 17 00:00:00 2001 From: Itamar Oren Date: Mon, 23 Nov 2026 19:44:38 -0800 Subject: [PATCH 2/4] Address review feedback --- Doc/extending/embedding.rst | 82 ++++++++++++++++++++++++------------- 1 file changed, 53 insertions(+), 29 deletions(-) diff --git a/Doc/extending/embedding.rst b/Doc/extending/embedding.rst index a7604de6604258c..a3cbe1224dbafdf 100644 --- a/Doc/extending/embedding.rst +++ b/Doc/extending/embedding.rst @@ -414,13 +414,18 @@ the Limited API and must *also* avoid the versioned dependency. A Python built with :option:`--enable-shared` and without :option:`--with-pydebug` installs :file:`libpython3.so` next to the versioned library. -This library defines no Python symbols itself. -It only depends on the versioned library, which the dynamic loader loads -along with it. -Linking an executable with ``-lpython3`` therefore fails with -``undefined reference`` errors, but an application can load -:file:`libpython3.so` with :manpage:`dlopen(3)` and look up each function that -it uses with :manpage:`dlsym(3)`. +When the dynamic loader loads this library, it also loads the versioned +library that it was built with, and symbols looked up through +:file:`libpython3.so` are found in the versioned library. +An application can therefore load :file:`libpython3.so` with +:manpage:`dlopen(3)` and look up each function that it uses with +:manpage:`dlsym(3)`. + +This only works at run time. +When linking an executable, the linker does not use the dependencies of a +library to resolve symbols, and :file:`libpython3.so` defines no Python +symbols of its own, so linking with ``-lpython3`` fails with +``undefined reference`` errors. For example, with Python 3.12 as the oldest supported version:: @@ -432,14 +437,14 @@ For example, with Python 3.12 as the oldest supported version:: /* The API this application uses, declared as in Python.h. Everything is reached through these pointers. */ static struct { - const unsigned long *Version; /* Py_Version */ - const char *(*GetVersion)(void); /* Py_GetVersion */ - void (*InitializeEx)(int); /* Py_InitializeEx */ - int (*FinalizeEx)(void); /* Py_FinalizeEx */ + const unsigned long *Version; + const char *(*GetVersion)(void); + void (*InitializeEx)(int); + int (*FinalizeEx)(void); } py; - #define LOAD(lib, name) \ - ((*(void **)&py.name = dlsym(lib, "Py_" #name)) != NULL) + #define LOAD(lib, pointer, name) \ + ((*(void **)&(pointer) = dlsym(lib, name)) != NULL) int main(int argc, char *argv[]) @@ -451,13 +456,17 @@ For example, with Python 3.12 as the oldest supported version:: argv[0]); return 2; } + /* RTLD_GLOBAL is required: it lets the extension modules that + Python imports find Python's symbols. */ void *lib = dlopen(argv[1], RTLD_NOW | RTLD_GLOBAL); if (lib == NULL) { fprintf(stderr, "Python is not available: %s\n", dlerror()); return 1; } - if (!LOAD(lib, Version) || !LOAD(lib, GetVersion) - || !LOAD(lib, InitializeEx) || !LOAD(lib, FinalizeEx)) + if (!LOAD(lib, py.Version, "Py_Version") + || !LOAD(lib, py.GetVersion, "Py_GetVersion") + || !LOAD(lib, py.InitializeEx, "Py_InitializeEx") + || !LOAD(lib, py.FinalizeEx, "Py_FinalizeEx")) { fprintf(stderr, "Unsupported Python: %s\n", dlerror()); return 1; @@ -473,18 +482,23 @@ For example, with Python 3.12 as the oldest supported version:: } Compile the program with Python's headers, but without the output of -``--ldflags``. +``--ldflags``: .. code-block:: shell-session $ gcc $(/opt/bin/python3.12-config --includes) -o myapp myapp.c - $ readelf -d myapp | grep NEEDED - 0x0000000000000001 (NEEDED) Shared library: [libc.so.6] $ ./myapp /usr/local/lib/libpython3.so Loaded Python 3.14.10 (main, Nov 5 2026, 09:47:10) [GCC 14.2.0] No Python library is passed to the linker, so the executable does not depend on one. +You can check this with ``readelf``: + +.. code-block:: shell-session + + $ readelf -d myapp | grep NEEDED + 0x0000000000000001 (NEEDED) Shared library: [libc.so.6] + For the same reason, Python functions can only be called through such pointers. This includes the functions that macros in :file:`Python.h` expand to: @@ -492,19 +506,30 @@ for example, call :c:func:`Py_DecRef` through a pointer instead of using :c:func:`Py_DECREF`. * The path passed to ``dlopen()`` selects the code that runs in your process. - Use an absolute path that comes from a trusted source and that names a file - only trusted users can replace. -* The dynamic loader looks for the versioned library by name in its usual - search path, such as :envvar:`!LD_LIBRARY_PATH` and the system library - directories, and not next to :file:`libpython3.so`. + It should come from a trusted source and name a file that only trusted + users can replace. +* Use an absolute path. + The dynamic loader looks for a name without a slash in its usual search + path, such as :envvar:`!LD_LIBRARY_PATH` and the system library directories. + It looks for the versioned library that :file:`libpython3.so` depends on in + the same way, and not next to :file:`libpython3.so`. To choose the exact file, pass the absolute path of the versioned library to ``dlopen()`` instead. * ``RTLD_GLOBAL`` makes Python's symbols available to the extension modules that Python imports, which are normally not linked against a Python library. -An existing application that calls the C API directly can instead be linked -as described :ref:`above `, and have the dependency recorded in -the executable renamed afterwards, for example with +.. rubric:: Alternative: renaming the dependency after linking + +Loading Python at run time, as described above, +is the preferred way to run one binary with several Python versions, +and it does not need anything described below. + +The following is a packaging workaround for an existing application that +calls the C API directly and cannot easily be changed. +It is not recommended; use it at your own risk. + +Such an application is linked as described :ref:`above `. +The dependency recorded in the executable is then renamed, for example with `patchelf `__: .. code-block:: shell-session @@ -513,9 +538,8 @@ the executable renamed afterwards, for example with .. warning:: - This is a packaging workaround. - It does not make the application compatible with other Python versions, - and it has additional limitations and caveats: + Renaming the dependency does not make the application compatible with + other Python versions, and it has additional limitations and caveats: * Renaming the dependency does not check that the application uses only the Stable ABI. From 8db57caa9a2e58de4a41f80957dc9d2b39c4df26 Mon Sep 17 00:00:00 2001 From: Itamar Oren Date: Tue, 24 Nov 2026 09:11:21 -0800 Subject: [PATCH 3/4] Call the patchelf approach "unsupported" --- Doc/extending/embedding.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Doc/extending/embedding.rst b/Doc/extending/embedding.rst index a3cbe1224dbafdf..112d76527e62ebf 100644 --- a/Doc/extending/embedding.rst +++ b/Doc/extending/embedding.rst @@ -518,7 +518,7 @@ for example, call :c:func:`Py_DecRef` through a pointer instead of using * ``RTLD_GLOBAL`` makes Python's symbols available to the extension modules that Python imports, which are normally not linked against a Python library. -.. rubric:: Alternative: renaming the dependency after linking +.. rubric:: Unsupported alternative: renaming the dependency after linking Loading Python at run time, as described above, is the preferred way to run one binary with several Python versions, @@ -526,7 +526,7 @@ and it does not need anything described below. The following is a packaging workaround for an existing application that calls the C API directly and cannot easily be changed. -It is not recommended; use it at your own risk. +It is unsupported and not recommended; use it at your own risk. Such an application is linked as described :ref:`above `. The dependency recorded in the executable is then renamed, for example with From bba683e16d9fc79ba894acef6dc2968ad217dafb Mon Sep 17 00:00:00 2001 From: Itamar Oren Date: Wed, 25 Nov 2026 10:57:09 -0800 Subject: [PATCH 4/4] Reduce the workaround patchelfing section --- Doc/extending/embedding.rst | 47 +++++++++---------------------------- 1 file changed, 11 insertions(+), 36 deletions(-) diff --git a/Doc/extending/embedding.rst b/Doc/extending/embedding.rst index 112d76527e62ebf..7d06f7a5c46b3d1 100644 --- a/Doc/extending/embedding.rst +++ b/Doc/extending/embedding.rst @@ -515,44 +515,19 @@ for example, call :c:func:`Py_DecRef` through a pointer instead of using the same way, and not next to :file:`libpython3.so`. To choose the exact file, pass the absolute path of the versioned library to ``dlopen()`` instead. -* ``RTLD_GLOBAL`` makes Python's symbols available to the extension modules - that Python imports, which are normally not linked against a Python library. +* ``RTLD_GLOBAL`` is required. + Extension modules are generally not linked against a Python library, + so Python can only import them if its symbols are visible globally. -.. rubric:: Unsupported alternative: renaming the dependency after linking +.. rubric:: Unsupported workaround: renaming the dependency after linking -Loading Python at run time, as described above, -is the preferred way to run one binary with several Python versions, -and it does not need anything described below. - -The following is a packaging workaround for an existing application that -calls the C API directly and cannot easily be changed. -It is unsupported and not recommended; use it at your own risk. - -Such an application is linked as described :ref:`above `. -The dependency recorded in the executable is then renamed, for example with -`patchelf `__: - -.. code-block:: shell-session - - $ patchelf --replace-needed libpython3.12.so.1.0 libpython3.so myapp +Some applications are instead linked against a versioned library as described +:ref:`above `, and the dependency recorded in the executable is +then renamed to :file:`libpython3.so`, for example with ``patchelf``. .. warning:: - Renaming the dependency does not make the application compatible with - other Python versions, and it has additional limitations and caveats: - - * Renaming the dependency does not check that the application uses only - the Stable ABI. - Compile it with :c:macro:`Py_LIMITED_API` defined, as described in - :ref:`abi3-compiling`. - * If the application refers to a Python data symbol directly, for example - ``&PyLong_Type``, the linker may have used a copy relocation. - This reserves space for the object in the executable, using its size in - the Python version that the application was linked against. - That size is not part of the Stable ABI and can differ between versions. - Look for such relocations with ``readelf -rW myapp | grep COPY``, and - compile the application as position-independent code (``-fPIC``) to - avoid them. - * The dynamic loader must find :file:`libpython3.so` in its search path - when the application starts. - Otherwise the application does not start at all. + Renaming the dependency this way is unsupported. + Nothing checks that such an executable only uses the Stable ABI, and it + can contain copies of Python data, such as ``PyLong_Type``, whose size + differs between Python versions.