Skip to content

Instantly share code, notes, and snippets.

@maxk42
Created July 14, 2024 19:35
Show Gist options
  • Save maxk42/7785fd645ab7351e291a06814b9f09d9 to your computer and use it in GitHub Desktop.
Save maxk42/7785fd645ab7351e291a06814b9f09d9 to your computer and use it in GitHub Desktop.
Compiling python to executable via cython

I'm creating this gist because it has taken me far too long to find information on how to build python into an executable via cython. There are two key pieces of information you need after installing cython and a compiler: (I'll use gcc for this example.)

  1. Compiler flags need to be linked via the python3-config command.
  2. The python3-config command and the cython command both need to be invoked with the --embed flag.

For this exercise, we'll start with a file called hello.py with the following contents:

print("Hello, World!")

The first step is to compile to C via cython:

cython --embed hello.py

This will create a file called hello.c. Next, compile with flags provided by the python3-config command. If you do not have this command installed on your system, you may need to install the python3-devel package. Depending on your system this may be called something else, such as libpython-dev.

gcc $(python3-config --cflags --embed) -o hello $(python3-config --embed --ldflags) hello.c

Remember that the order of the flags is important, and the ldflags must come after the object file name (-o hello). If all went smoothly, this will generate a file called hello that will be executable.

This has been tested on both OS X (M2 arm64 architecture) and Linux CentOS (AMD x86_64 architecture). Feel free to ping me if you have questions as I'd prefer to help others avoid the absolutely embarassing amount of hours I put into figuring this out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment