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

标签 python c gcc compilation cython

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

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

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

$ 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-script 工作得很好,但在模块上工作时,它们都不是很方便。

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

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


*pyximport:导入的模块中只包含python-native函数和类而不包含cdef-functions和类是否正常? 喜欢:

# 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" 会杀死 undefined reference to -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'

最佳答案

试试:

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

关于python - 如何使用 gcc 从 Cython 编译 .c 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6985109/

相关文章:

python - 在 scikit-learn 中为新数据保存特征向量

c - 了解古代 C 中的动态分配

c - 如何在 C 的初始化程序中使用 static_assert?

c - 如何在 C 函数中使用全局结构引用填充结构指针?

gcc - 将 Binutils 从 2.16.1 升级到 2.19 是否有优势?为什么?

c - 重新加载共享库时,带有__attribute __(constructor)标记的函数是否再次运行?

python - 长时间运行的进程中的 SQLAlchemy session 管理

python - 区域设置与 Power BI 中用于 Python 可视化的 Matplotlib 冲突

gcc - valgrind、gcc 6.2.0 和 "-fsanitize=address"

python - 是否有用于实时视频输入的 Python 库?