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.)
- Compiler flags need to be linked via the
python3-configcommand. - The
python3-configcommand and thecythoncommand both need to be invoked with the--embedflag.
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.pyThis 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.cRemember 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.