Linux 使用 Cython 将 Python 编译为 C

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4421832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 00:17:20  来源:igfitidea点击:

Compiling Python to C using Cython

pythonclinuxgcccython

提问by Forge

I'm trying to compile pythonsource code foo.py to C using cython.

我正在尝试将python源代码 foo.py编译为 C 使用cython.

In foo.py:

foo.py

print "Hello World"

The command I'm running is cython foo.py.

我正在运行的命令是cython foo.py.

The problem is that when compiling foo.c using gcc, I get the error:

问题是,在使用 编译 foo.c 时gcc,出现错误:

undefined reference to 'main'.

undefined reference to 'main'.

采纳答案by RoeeK

when converting the code from python to c (using Cython) it converts it to c code which can be compiled into a shared object. in order to make it executable, you should add "--embed" to cython conversion command. this flag adds the 'main' function you need, so you could compile the c code into executable file. please notice you'll need the python .soruntime libraries in order to run the exec.

将代码从 python 转换为 c(使用 Cython)时,它会将其转换为可以编译为共享对象的 c 代码。为了使其可执行,您应该在 cython 转换命令中添加“--embed”。这个标志添加了你需要的'main'函数,所以你可以将c代码编译成可执行文件。请注意,您需要 python.so运行时库才能运行 exec。

回答by Forge

Read the Cython documentation. This will also (hopefully) teach you what Cython is and what it isn't. Cython is for creating python extensions (not a general-purpose Python-to-C-compiler), which are shared objects/dlls. Dynamically loaded libraries don't have a mainfunction like standalone programs, but compilers assume that they are ultimately linking an executable. You have to tell them otherwise via flags (-sharedmethinks, but again, refer to the Cython documentation) - or even better, don't compile yourself, use a setup.pyfor this (yet again, read the Cython documentation).

阅读 Cython 文档。这也将(希望)教你 Cython 是什么,它不是什么。Cython 用于创建 python 扩展(不是通用的 Python 到 C 编译器),它们是共享对象/dll。动态加载的库main不像独立程序那样具有功能,但编译器假定它们最终链接的是可执行文件。您必须通过标志告诉他们其他情况(我认为-shared,但再次参考 Cython 文档) - 或者甚至更好,不要自己编译,setup.py为此使用 a (再次阅读 Cython 文档)。

回答by Fabian Pedregosa

The usual way is to use distutils to compile the cython-generated file. This also gives you all the include directories you need in a portable way.

通常的方法是使用 distutils 编译 cython 生成的文件。这也以可移植的方式为您提供了所需的所有包含目录。