I need help splitting the python c-api module into several files to better structure the project.
The main file module_core.c contains the program code:
#include "my_module.h"
static PyMethodDef init_methods[] = {
{"hello", init_hello, METH_VARARGS, "Welcome stamp"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef init_module = {
PyModuleDef_HEAD_INIT,
"init",
"Module for displaying a greeting",
-1,
init_methods
};
static PyObject* init_init_module(PyObject *module) {
PyObject* module_dict = PyModule_GetDict(module);
if (module_dict == NULL) {
return NULL;
}
if (PyEval_EvalCode(Py_CompileString("init.hello()", "<string>", Py_file_input),
module_dict, module_dict) == NULL) {
PyErr_Print();
return NULL;
}
PyRun_SimpleString("print(dir())");
Py_RETURN_NONE;
}
PyMODINIT_FUNC PyInit_init(void) {
PyObject *m = PyModule_Create(&init_module);
if (m == NULL)
return NULL;
if (PyModule_AddObject(m, "init", m) < 0) {
Py_DECREF(m);
return NULL;
}
// Call the function to print "Hello world!" when importing
if (init_init_module(m) < 0) {
Py_DECREF(m);
return NULL;
}
return m;
}
the file my_module.h has the following code:
#ifndef MY_MODULE_H
#define MY_MODULE_H
#include <Python.h>
static PyObject* init_hello(PyObject* self, PyObject* args);
#endif
utils.c file has the following code:
#include "my_module.h"
static PyObject* init_hello(PyObject* self, PyObject* args) {
const char * python_code = "ndef bar():n print('test from foo')nnnbar()n";
PyRun_SimpleString("print('Hello, World!')");
PyRun_SimpleString(python_code);
Py_RETURN_NONE;
}
build file setup.py
from setuptools import setup, Extension
extensions = [
Extension(
"init",
sources=[
"my_module/module_core.c",
"my_module/utils.c",
],
extra_compile_args=["-O2", "-Wall"],
extra_link_args=[],
include_dirs=["my_module"],
),
]
setup(
name="init",
version="1.0.0",
description="Example Python module using C-API",
ext_modules=extensions
)
The module compiles successfully, but with warnings. After compiling and importing, the Python interpreter reports an error:
>> import init
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: /home/u/work3/app/init.cpython-310-x86_64-linux-gnu.so: undefined symbol: init_hello
Please help me resolve the error.