11

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

Forge
  • 6,538
  • 6
  • 44
  • 64

3 Answers3

26

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.

lothario
  • 1,788
  • 1
  • 14
  • 8
RoeeK
  • 1,112
  • 12
  • 23
9

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

  • 5
    for me this answer resulted in compilation of a working extension. answer of RoeeK resolved the linking problem, but after Python failed to import with error `ImportError: dynamic module does not define init function`. thank you really much, I think would be nicer to write it with less lecturing style without assuming stupidity as the 3 rtfm suggests. – deeenes Nov 19 '15 at 14:51
  • This answer would be perfect if it included a link to the [Cython docs](https://cython.readthedocs.io/en/latest/) and the [Cython FAQ](https://github.com/cython/cython/wiki/FAQ#how-can-i-run-doctests-in-cython-code-pyx-files). – 0p3r4t0r Jun 14 '20 at 06:01
  • Not a very helpful answer. It's basically a RTFM but wrong as proven by the accepted answer. – Adham Zahran Oct 14 '21 at 18:07
0

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.

DeadChex
  • 4,379
  • 1
  • 27
  • 34
Fabian Pedregosa
  • 6,329
  • 1
  • 22
  • 20