20

include

using namespace boost::python;

struct World{
    void set(std::string msg) { this->msg = msg; }
    std::string greet() { return msg; }
    std::string msg;
};

BOOST_PYTHON_MODULE(hello)
{
    class_<World>("World")
        .def("greet", &World::greet)
        .def("set", &World::set)
    ;
}

Compile and build ok

~/boost$ g++ -fPIC -I/usr/include/python2.6 -c hello.cpp 
~/boost$ g++ -shared hello.o -o hello.so

But when import from python side, got error.

>>> import hello.so
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: ./hello.so: undefined symbol: _ZNK5boost6python7objects21py_function_impl_base9max_arityEv
>>> 
H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
user216056
  • 313
  • 1
  • 3
  • 9

4 Answers4

14

Solved this via "No such file or directory" error with Boost Python

g++ -c -fPIC hello.cpp -o hello.o
g++ -shared -Wl,-soname,hello.so -o hello.so  hello.o -lpython2.6 -lboost_python

did the trick for me. I hope this is as clear as possible as i was struggling with this for about half an hour now ;)

Community
  • 1
  • 1
7

same as other post here

g++ -c -fPIC hello.cpp -o hello.o
g++ -shared -Wl,-soname,hello.so -o hello.so  hello.o -lpython2.6 -lboost_python

But i want to stress the importance of the position of "-lpython2.6 -lboost_python". If you put them in front of input files (hello.o), they will be somehow ignored (not linked to the final hello.so). This is at least true for g++ (Ubuntu/Linaro 4.6.3-1ubuntu5).

To be simple, http://ubuntuforums.org/showthread.php?t=496287 suggested:

  g++ <.cpp or .o file(s)> [LDFLAGS] [LIBS] -o [appname]
Yu Huang
  • 106
  • 1
  • 2
  • 4
    As I understand it, the reason for the link-order sensitivity is that the GNU `ld` compile-time linker is a one-pass linker: it picks up symbols to resolve from left-to-right on the command-line, and maintains a list of unresolved symbols, so if `hello.o` is at the end, it introduces new unresolved symbols (that are defined in `libpython2.6.so` and `libboost_python.so`), but they can't now be resolved because there's nothing *to the right* that defines those symbols. – Emmet Aug 30 '13 at 19:24
4

Oh, I just saw this post:

help needed with boost python

and problem solved

Community
  • 1
  • 1
user216056
  • 313
  • 1
  • 3
  • 9
3

I had the same issue and it turned out that I was missing a constructor on my class.

Jakobovski
  • 3,203
  • 1
  • 31
  • 38
  • Just had the same error, this one was so bloody sneaky!! Thanks a bunch for this remark, it could have taken me days until I noticed this – John C Aug 07 '17 at 12:44