Skip to content
Advertisement

compile official doc “Embedding Python in Another Application” example failed

I am trying to compile and run the example from https://docs.python.org/3/extending/embedding.html#very-high-level-embedding , but failed.

My environment is Ubuntu 20.04.2 LTS, with system shipped python3.8(statically built), libpython3-dev and libpython3.8-dev packages installed.


What I’ve tried:

main.c :

JavaScript

From https://docs.python.org/3/extending/embedding.html#compiling-and-linking-under-unix-like-systems, get gcc flags.

JavaScript

(I don’t know why python3-config output has some duplicated values, that’s not a typing mistake)

gcc {copy cflags output} -o main main.c /path_to_libpython/libpython3.8.a {copy ld flags output}:

JavaScript

make test1 gives error, nearly all related to -fPIE error:

JavaScript

I saw there is a /usr/lib/python3.8/config-3.8-x86_64-linux-gnu/libpython3.8-pic.a and tried link it instead but also failed (log).


Later I tried a Docker image(python:3.10.5-bullseye) with share build python and succeeded.

JavaScript
JavaScript

(I add -lpython3.10 in the end)

It compiles and ./main :

JavaScript

What’s wrong with my compilation for the Ubuntu system shipped, python3.8 one?

Anyway, I just want to validate that I can link the static python library libpythonx.y.a . So if anyone can make that work on a fresh installed machine or with non system shipped python (e.g. self-built static python), I’d like to try.

Advertisement

Answer

I made more experiments on both system shipped python and self built python libraries. For self bulilt pythons, it’s easy to compile successfully, either for shared built python or statically built python.

For system shipped python, shared link is easy and what I’ve missed for static link is that I need to link 2 extra libs -lexpat and -lz. Also there are 2 ways for system shipped python to link successfully:

  1. Add -no-pie, and -lexpat -lz.
  2. No -no-pie, use libpython3.8-pic.a, and -lexpat -lz.

Check the py38_system_static target below.

makefile:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement