如何使用 gcc 从 Cython 编译 .c 代码

2024-01-04

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

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

使用gcc编译代码会抛出几十个未定义的引用-错误,我很确定libpython.a可用(如安装教程所述,未定义的引用- 如果该文件丢失,则会抛出错误)。

$ 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* or a setup-script 工作得很好,但是当仍在处理模块时,它并不是很方便。

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

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

*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

UPDATE

Calling $ gcc ctest.c "C:\Python27\libs\libpython27.a"杀死未定义的引用- 错误,但是这个:

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

Try:

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 的链接。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 gcc 从 Cython 编译 .c 代码 的相关文章