1

I am interested in using Boost.Python to call C++ functions from my Python scripts.

This example here is an introductory example on Boost python's home-pagewhich I am unable to run. Can someone help me out with this?

This is what I tried

I created a file named hello_ext.cpp as follows

#include <boost/python.hpp>
char const* greet()
{
   return "hello, world";
}


BOOST_PYTHON_MODULE(hello_ext)
{
    using namespace boost::python;
    def("greet", greet);
}

I then compiled it to a shared library as follows

g++ -c -Wall -Werror -fpic hello_ext.cpp -I/usr/include/python2.7
g++ -shared -o libhello_ext.so hello_ext.o

Finally firing up the ipython interpreter I tried to import hello_ext but got the following error message. Where did I go wrong?

In [1]: import hello_ext
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-18c4d6548768> in <module>()
----> 1 import hello_ext

ImportError: ./hello_ext.so: undefined symbol: _ZNK5boost6python7objects21py_function_impl_base9max_arityEv
2
  • You need to link libhello_ext.so with libboost_python. Commented Jan 14, 2016 at 23:41
  • @ n.m. Thank you! Can you tell me how I should do that? Will I need to modify the first or the second line? Commented Jan 14, 2016 at 23:49

1 Answer 1

3

You should include some libraries in your link command,

 g++ -shared -Wl,--no-undefined hello_ext.o -lboost_python -lpython2.7 -o hello_ext.so

With -Wl,--no-undefined linker option it will be an error if some symbols are missing.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! It looks like it cannot find the libboost_python library. It seems not to be installed. Anyway I'll accept this answer for now! Thanks.
Afaik object file and libraries need to be stated in the proper order in the linker call, with the dependent module first: g++ -shared -Wl,--no-undefined -o hello_ext.so hello_ext.o -lboost_python -lpython2.7
@jomuel Oh thanks so much! The code was still not compiling. It works fine now!
@jomuel I guess g++ / ld may allow one to get away with that wrong link order. If I remember correctly, link order has usually mattered more in case of static libraries. I edited my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.