Greg Nisbet
Greg Nisbet

Reputation: 6994

Manually build a shared object using boost::python

I'm trying to create a shared object using boost::python (installed through homebrew) that's loadable in Python on OS X using the Python 2.7 that ships with the OS. What libraries do I have to link in to get a usable shared object?

Here's hello_ext.cpp, taken from the tutorial

// hello_ext.cpp
char const* greet() {
  return "hello, world";
}

#include <boost/python.hpp>

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

I can compile the example like this, although it takes a while.

$ clang++ -fPIC -c -I/usr/include/python2.7 hello_ext.cpp

However, when I attempt to link it and produce an so I get a bunch of undefined symbols:

$ clang++ -shared -o hello_ext.so hello_ext.o | & head -n 7
Undefined symbols for architecture x86_64:
  "_PyString_Type", referenced from:
      boost::python::to_python_value<char const* const&>::get_pytype() const in hello_ext.o
  "__Py_NoneStruct", referenced from:
      boost::python::api::object::object() in hello_ext.o
  "boost::python::detail::init_module(char const*, void (*)())", referenced from:
      _inithello_ext in hello_ext.o

Some of them clearly come from the Python interpreter, and indeed -lpython solves some of the unresolved symbol errors:

$ clang++ -shared -o hello_ext.so hello_ext.o -lpython | & head -n 7
Undefined symbols for architecture x86_64:
  "boost::python::detail::init_module(char const*, void (*)())", referenced from:
      _inithello_ext in hello_ext.o
  "boost::python::detail::gcc_demangle(char const*)", referenced from:
      boost::python::type_info::name() const in hello_ext.o
  "boost::python::detail::scope_setattr_doc(char const*, boost::python::api::object const&, char const*)", referenced from:
      void boost::python::def<char const* (*)()>(char const*, char const* (*)()) in hello_ext.o

The documentation here for boost::python goes into some detail about how to use the library in conjunction with cmake, but doesn't say much about what libraries are required at link time.

Upvotes: 0

Views: 309

Answers (1)

n. m. could be an AI
n. m. could be an AI

Reputation: 119847

boost::python is not a header-only library, it includes a binary component. You need to link with it, for example

clang++ ... -I/usr/include/python2.7 -lboost_python -lpython2.7  

The library is apparently installed by the homebrew package boost-python, not boost.

Upvotes: 1

Related Questions