Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

getting `undefined symbol` errors when trying to import shared library written in c++ in python session

I was following this tutorial from boost.python to create a shared library. Here's a simple code defining the methods that I want to expose to python.

#include <boost/python.hpp>
#include <iostream>

const int oneforth(int num, int bound) {
    if (num < bound) {return num;}
    return oneforth(num * (1/4), bound);
}


BOOST_PYTHON_MODULE(modd) //python module name
{
    using namespace boost::python;
    def("oneforth", oneforth); //python method
}


int main() {
    std::cout << oneforth(10, 4);
    return 0;
}
ai

I want to expose oneforth function so I can use from modd import oneforth.

I'm building the shared library *.so using -

g++ -c -fPIC py.cpp -o py.o
g++ -shared py.so  py.o

whenever I trying to import the dynamic py.so, I get erros like undefined symbol. What am I doing wrong? How does one create a shared library this way?

question from:https://stackoverflow.com/questions/66068038/getting-undefined-symbol-errors-when-trying-to-import-shared-library-written-i

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I tried to reproduce this and got two different error messages 'like undefined symbol'. I'll explain both since I'm not 100% sure which one you encountered.

this first was:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: /mnt/tmpfs/py.so: undefined symbol: _ZNK5boost6python7objects21py_function_impl_base9max_arityEv

the undefined symbol here is a mangled c++ name boost::python::objects::py_function_impl_base::max_arity() const wich can be found in libboost_python39.so for example. This means you have to link your library with -lboost_python39 to make this symbol available.

the second was:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: dynamic module does not define module export function (PyInit_py)

This one went away when I gave library file the module name that is mentioned in the source code modd.so. I have never used boost_python before so I can't guarantee that this is in fact what the error means.

TL;TR

I got it working by changing the second build line to

g++ -shared -o modd.so py.o -lboost_python39

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...