Forge
Forge

Reputation: 6834

Compiling Python to C using Cython

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'.

Upvotes: 12

Views: 18235

Answers (3)

Fabian Pedregosa
Fabian Pedregosa

Reputation: 6539

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.

Upvotes: 0

RoeeK
RoeeK

Reputation: 1162

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.

Upvotes: 27

user395760
user395760

Reputation:

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).

Upvotes: 9

Related Questions