Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

python - How to compile .c code from Cython with gcc

Now that I've successfully installed Cython on Windows 7, I try to compile some Cython code using Cython, but gcc makes my life hard.

cdef void say_hello(name):
    print "Hello %s" % name

Using gcc to compile the code throws dozens of undefined reference to -erros, and I'm pretty sure the libpython.a is available (as the installation tutorial said, undefined reference to -errors are thrown if this file is missing).

$ cython ctest.pyx
$ gcc ctest.c -I"C:Python27include"

C:Users
iklasAppDataLocalTempcckThGrF.o:ctest.c:(.text+0x1038): undefined reference to `_imp__PyString_FromStringAndSize'
C:Users
iklasAppDataLocalTempcckThGrF.o:ctest.c:(.text+0x1075): undefined reference to `_imp___Py_TrueStruct'
C:Users
iklasAppDataLocalTempcckThGrF.o:ctest.c:(.text+0x1086): undefined reference to `_imp___Py_ZeroStruct'
C:Users
iklasAppDataLocalTempcckThGrF.o:ctest.c:(.text+0x1099): undefined reference to `_imp___Py_NoneStruct'
C:Users
iklasAppDataLocalTempcckThGrF.o:ctest.c:(.text+0x10b8): undefined reference to `_imp__PyObject_IsTrue'
c:/program files/mingw/bin/../lib/gcc/mingw32/4.5.2/../../../libmingw32.a(main.o):main.c:(.text+0xd2): undefined reference to `WinMain@16'
collect2: ld returned 1 exit status

The weird thing is, using pyximport* or a setup-script works pretty fine, but it's both not very handy when still working on a module.

How to compile those .c files generated with Cython using gcc ?

or any other compiler, important is that it will work !


*pyximport: Is it normal that only python-native functions and classes are contained in the imported module and not cdef-functions and classes ? like:

# filename: cython_test.pyx
cdef c_foo():
    print "c_foo !"
def foo():
    print "foo !"
    c_foo()

import pyximport as p; p.install()
import cython_test
cython_test.foo()
# foo !
c_foo !
cython_test.c_foo()
# AttributeError, module object has no attribute c_foo


UPDATE

Calling $ gcc ctest.c "C:Python27libslibpython27.a" kills the undefined reference to -erros, but this one:

c:/program files/mingw/bin/../lib/gcc/mingw32/4.5.2/../../../libmingw32.a(main.o):main.c:(.text+0xd2): undefined reference to `WinMain@16'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try:

gcc -c -IC:Python27include -o ctest.o ctest.c
gcc -shared -LC:Python27libs -o ctest.pyd ctest.o -lpython27

-shared creates a shared library. -lpython27 links with the import library C:Python27libslibpython27.a.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...