Compiling Python to C using Cython

2020-07-04 05:02发布

问题:

I'm trying to compile python source code foo.py to C using cython.

In foo.py:

print "Hello World"

The command I'm running is cython foo.py.

The problem is that when compiling foo.c using gcc, I get the error:

undefined reference to 'main'.

回答1:

when converting the code from python to c (using Cython) it converts it to c code which can be compiled into a shared object. in order to make it executable, you should add "--embed" to cython conversion command. this flag adds the 'main' function you need, so you could compile the c code into executable file. please notice you'll need the python .so runtime libraries in order to run the exec.



回答2:

Read the Cython documentation. This will also (hopefully) teach you what Cython is and what it isn't. Cython is for creating python extensions (not a general-purpose Python-to-C-compiler), which are shared objects/dlls. Dynamically loaded libraries don't have a main function like standalone programs, but compilers assume that they are ultimately linking an executable. You have to tell them otherwise via flags (-shared methinks, but again, refer to the Cython documentation) - or even better, don't compile yourself, use a setup.py for this (yet again, read the Cython documentation).



回答3:

The usual way is to use distutils to compile the cython-generated file. This also gives you all the include directories you need in a portable way.