在 Ubuntu 系统中,gcc 是用于编译 C 语言程序的编译器,而不是直接用于 Python 语言编程。但是,如果你想使用 gcc 来编译包含 Python C API 的扩展模块,你可以这样做。以下是基本步骤:
安装 Python 开发包: 确保你已经安装了 Python 的开发包,这通常包括 Python 的头文件和静态库,这对于编译扩展模块是必需的。
sudo apt-get update
sudo apt-get install python3-dev # 对于 Python 3.x
# 或者
sudo apt-get install python-dev # 对于 Python 2.x
编写 Python 扩展模块:
创建一个 .c 文件,例如 hello.c,并使用 Python C API 编写你的扩展模块代码。
#include <Python.h>
static PyObject* say_hello(PyObject* self, PyObject* args) {
printf("Hello, World!\n");
Py_RETURN_NONE;
}
static PyMethodDef HelloMethods[] = {
{"say_hello", say_hello, METH_NOARGS, "Prints 'Hello, World!'"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef hellobuild = {
PyModuleDef_HEAD_INIT,
"hello", /* name of module */
NULL, /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. */
HelloMethods
};
PyMODINIT_FUNC
PyInit_hello(void)
{
return PyModule_Create(&hellobuild);
}
编译扩展模块:
使用 gcc 编译你的 .c 文件来创建一个 Python 可以导入的共享库。
gcc -I/usr/include/python3.8 -fPIC -shared -o hello.so hello.c $(python3-config --ldflags)
这里 -I/usr/include/python3.8 是 Python 头文件的路径(根据你的 Python 版本和安装位置可能需要调整),-fPIC 生成位置无关代码,-shared 创建共享库,-o hello.so 指定输出文件名为 hello.so,$(python3-config --ldflags) 获取链接 Python 扩展模块所需的标志。
使用扩展模块: 在 Python 中导入并使用你的扩展模块。
import hello
hello.say_hello()
请注意,如果你只是想编写 Python 脚本,通常不需要使用 gcc。Python 是一种解释型语言,你可以直接使用文本编辑器编写 .py 文件,并通过 Python 解释器运行它们。gcc 主要用于编译那些需要编译成机器码的程序,或者像上面这样的 Python 扩展模块。