c++ extension for python throws 'symbol not found in flat namespace (__ZL10func1P7_objectS0_)' error on import

417 views Asked by At

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.

0

There are 0 answers