在 CPython 中,Py_Main 的范围在哪里?

In CPython, where does Py_Main get put in scope?

我一直在查看 CPython 源代码,其中 python.h 对大多数模块进行导入。仅通过跟踪代码,我找不到将 Py_Main() 例程放入范围的点。

我确实在 Modules/main.c 中找到了 Py_Main 的定义,以及 include/pylifecycle.h 中的原型,我似乎无法拼凑它是从哪里导入的,或者如果这是在链接器级别使用 make.

完成的

TLDR: #include "python.h"Py_Main 现在在范围内...它是在什么时候注入的?

Py_Mainpylifecycle.h:

中声明
PyAPI_FUNC(int) Py_Main(int argc, wchar_t **argv);

pylifecycle.h 包含在 Python.h:

#include "pylifecycle.h"

每当您写 #include "Python.h" 时,pylifecycle.h 会自动包含在内,您会得到 Py_Main.

这是关于函数声明的,现在它的代码呢?

对于 CPython 本身:

构建Python时,Python directory gets compiled into an object (.o) file by the C compiler. Objects files are then statically linked together into a standalone executable. On Linux, the usual linker is GNU ld.

中的每个.c文件

对于第三方模块:

对于想要使用 Python API 的模块,不包括 Py_Main 的代码:它由 dynamic linker 在运行时加载。

在 Linux 上(以及类似地,在其他系统上)编译后的 Python 代码以两种方式发布:作为独立的可执行文件 python,以及作为共享库 python.so。两者都包含 Py_Main 和所有其他函数的代码。