0

I'm writing a c++ extension module for python and all of the static functions have to be in the same file with the main module init function to prevent a symbol not in flat namespace error.

module.cpp:

#include "tech.h"

...

static PyMethodDef methods[] = {
    {"func1", (PyCFunction)func1, METH_VARARGS, "..."},
    {"func2", (PyCFunction)func2, METH_VARARGS, "..."},
    {NULL, NULL, 0, NULL}};

static PyModuleDef tech_module = {
    PyModuleDef_HEAD_INIT,
    "test_cpp",
    "...",
    0,
    tech_methods};

PyMODINIT_FUNC PyInit_test_cpp()
{
    return PyModule_Create(&tech_module);
}

lib1.cpp:

static PyObject *func1(PyObject *self, PyObject *args) {
    ...
}

lib2.cpp:

static PyObject *func2(PyObject *self, PyObject *args) {
    ...
}

tech.h:

...
static PyObject *func1(PyObject *self, PyObject *args);
static PyObject *func2(PyObject *self, PyObject *args);

setup.py

from setuptools import setup, Extension, find_packages
from os import environ

environ["CC"] = "/usr/bin/g++"

setup(
    name="test",
    version="1.0",
    packages=find_packages("."),
    ext_modules=[
        Extension(
            "test_cpp",
            include_dirs=[
                "/usr/local/Cellar/boost/1.79.0_2/include/",
                "/usr/local/include/",
            ],
            sources=[
                "cpp/tech/module.cpp",
                "cpp/tech/lib1.cpp",
                "cpp/tech/lib2.cpp",
            ],
            extra_compile_args=["-std=c++20"],
        )
    ],
)

The module works in Python if I move the definitions of two functions to module.cpp and compilation passes on both scenarios as expected. But is there any way I can define functions in other files. I'd not like to write all of them in one file. I'm using MacOS Monterey. Thanks.

VD26
  • 138
  • 2
  • 12
  • `import "tech.h"` ?? I think it is like the traditional preprocessor way `#include "tech.h"`. Or with the brand new C++20 modules feature, it would be `import tech;` – prapin Jan 16 '23 at 21:38
  • 1
    How exactly does this involve pybind11? – Dan Mašek Jan 16 '23 at 21:52
  • `import "tech.h"` is a C++20 header unit. – unddoch Jan 16 '23 at 22:00
  • sorry that is a typo. I added it by hand. – VD26 Jan 16 '23 at 22:06
  • @DanMašek I mean I used pybind in some of the functions. Although this issue is not likely associated with pybind, it is a pretty niched problem that people with python c++ extension and pybind experience might have some insights for. – VD26 Jan 16 '23 at 22:09
  • You have declared non-member functions as static which affects their linkage. See [this](https://stackoverflow.com/questions/8406800/when-should-i-write-the-keyword-static-before-a-non-member-function). – ChrisD Jan 18 '23 at 04:15

0 Answers0