如何用g从Cython编译.c代码

2024-09-28 22:24:00 发布

您现在位置:Python中文网/ 问答频道 /正文

现在我已经成功地在Windows 7上安装了Cython,我试着用Cython编译一些Cython代码,但是gcc让我的生活变得艰难。

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

使用gcc编译代码会抛出几十个未定义的对-erros的引用,我确信libpython.a是可用的(正如安装教程所说,如果缺少此文件,则会抛出未定义的对-errors的引用)。

$ cython ctest.pyx
$ gcc ctest.c -I"C:\Python27\include"

C:\Users\niklas\AppData\Local\Temp\cckThGrF.o:ctest.c:(.text+0x1038): undefined reference to `_imp__PyString_FromStringAndSize'
C:\Users\niklas\AppData\Local\Temp\cckThGrF.o:ctest.c:(.text+0x1075): undefined reference to `_imp___Py_TrueStruct'
C:\Users\niklas\AppData\Local\Temp\cckThGrF.o:ctest.c:(.text+0x1086): undefined reference to `_imp___Py_ZeroStruct'
C:\Users\niklas\AppData\Local\Temp\cckThGrF.o:ctest.c:(.text+0x1099): undefined reference to `_imp___Py_NoneStruct'
C:\Users\niklas\AppData\Local\Temp\cckThGrF.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

奇怪的是,使用pyximport*或setup脚本工作得很好,但在处理模块时,这两种脚本都不太方便。

如何编译那些使用gcc使用Cython生成的.c文件?

或任何其他编译器,重要的是它会工作!


*pyximport:导入的模块中只包含python本机函数和类,而不包含cdef函数和类,这正常吗? 比如:

# 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 !\nc_foo !
cython_test.c_foo()
# AttributeError, module object has no attribute c_foo


更新

调用$ gcc ctest.c "C:\Python27\libs\libpython27.a"可终止对-erros的未定义引用,但这一个:

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

Tags: totextfoolocalusersappdatatempcython
2条回答

这是一个链接器(ld)错误,而不是编译器错误。您应该提供库的路径(-l和-l),而不仅仅是头的路径(-I)。

尝试:

gcc -c -IC:\Python27\include -o ctest.o ctest.c
gcc -shared -LC:\Python27\libs -o ctest.pyd ctest.o -lpython27

-shared创建共享库。-lpython27链接到导入库C:\ Python27\libs\libpython27.a

相关问题 更多 >