如何用gcc编译Cython中的.c代码

27 投票
2 回答
25052 浏览
提问于 2025-04-16 23:08

现在我在Windows 7上成功安装了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*或者一个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"可以解决未定义引用的错误,但这个命令:

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

2 个回答

1

这是一个链接器(ld)错误,而不是编译器错误。你需要提供库的路径(使用 -l 和 -L),而不仅仅是头文件的路径(使用 -I)。

21

试试这个:

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。

撰写回答