Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile the Python interpreter statically?

I'm building a special-purpose embedded Python interpreter and want to avoid having dependencies on dynamic libraries so I want to compile the interpreter with static libraries instead (e.g. libc.a not libc.so).

I would also like to statically link all dynamic libraries that are part of the Python standard library. I know this can be done using Freeze.py, but is there an alternative so that it can be done in one step?

like image 849
Jeremy Cowles Avatar asked Jul 19 '09 17:07

Jeremy Cowles


People also ask

Can you statically compile Python?

It is possible to produce a fully statically linked executable embedding Python on Linux. The produced binary will have no external library dependencies nor will it even support loading dynamic libraries.

What is statically compiled?

A static build is a compiled version of a program which has been statically linked against libraries.

Are static libraries compiled?

In the C programming language, a static library is a compiled object file containing all symbols required by the main program to operate (functions, variables etc.)


1 Answers

I found this (mainly concerning static compilation of Python modules):

  • http://bytes.com/groups/python/23235-build-static-python-executable-linux

Which describes a file used for configuration located here:

<Python_Source>/Modules/Setup 

If this file isn't present, it can be created by copying:

<Python_Source>/Modules/Setup.dist 

The Setup file has tons of documentation in it and the README included with the source offers lots of good compilation information as well.

I haven't tried compiling yet, but I think with these resources, I should be successful when I try. I will post my results as a comment here.

Update

To get a pure-static python executable, you must also configure as follows:

./configure LDFLAGS="-static -static-libgcc" CPPFLAGS="-static" 

Once you build with these flags enabled, you will likely get lots of warnings about "renaming because library isn't present". This means that you have not configured Modules/Setup correctly and need to:

a) add a single line (near the top) like this:

*static* 

(that's asterisk/star the word "static" and asterisk with no spaces)

b) uncomment all modules that you want to be available statically (such as math, array, etc...)

You may also need to add specific linker flags (as mentioned in the link I posted above). My experience so far has been that the libraries are working without modification.

It may also be helpful to run make with as follows:

make 2>&1 | grep 'renaming' 

This will show all modules that are failing to compile due to being statically linked.

like image 167
Jeremy Cowles Avatar answered Oct 03 '22 19:10

Jeremy Cowles