如何使用 gcc 从 Cython 编译 .c 代码 [英] How to compile .c code from Cython with gcc

查看:44
本文介绍了如何使用 gcc 从 Cython 编译 .c 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我已经在 Windows 7 上成功安装了 Cython,我尝试使用 Cython 编译一些 Cython 代码,但是 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

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

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

奇怪的是,使用 pyximport* 或 setup-script 工作得很好,但是当仍然在处理模块时,它们都不是很方便.

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.

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


*pyximport:导入的模块中只包含 python 原生函数和类,而不包含 cdef 函数和类,这是否正常?喜欢:

*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


调用 $ gcc ctest.c "C:Python27libslibpython27.a" 会杀死 未定义的引用 -erros,但是这个:

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'

推荐答案

尝试:

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

-shared 创建一个共享库.-lpython27 与导入库 C:Python27libslibpython27.a. 的链接.

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

这篇关于如何使用 gcc 从 Cython 编译 .c 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆