0

When using the Python/C API to extend C++ to Python, should local C++ functions be declared as static?

#include <Python.h>

static PyObject* py_addNumbers(PyObject* self, PyObject* args) {
    int a, b;
    if (!PyArg_ParseTuple(args, "ii", &a, &b)) {
        return nullptr;
    }

    int result = a + b;
    return PyLong_FromLong(result);
}
PyMODINIT_FUNC PyInit_example(void) {
    static PyMethodDef ModuleMethods[] = {
        { "addNumbers", py_addNumbers, METH_VARARGS, "Add two numbers" },
        { nullptr, nullptr, 0, nullptr }
    };

    static PyModuleDef ModuleDef = {
        PyModuleDef_HEAD_INIT,
        "example",
        "Example module",
        -1,
        ModuleMethods
    };

    PyObject* module = PyModule_Create(&ModuleDef);
    return module;
}

For example, in the above example, the py_addNumbers function is declared as static. I saw in the official document that the native function is also declared as static. Why do you want to do this, or can you not do it?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
一小木
  • 1
  • 1
  • Please take some time to read about [storage and linkage](https://en.cppreference.com/w/cpp/language/storage_duration). [A good C++ book or two](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) should also be very helpful. – Some programmer dude Jun 18 '23 at 08:29
  • Since you're only referencing the function in `moduleMethods`, it doesn't need to be external. It won't be called by name from other compilation units, they just get the function pointer from `ModuleMethods`. – Barmar Jun 18 '23 at 08:48

0 Answers0