Z. Liu
Z. Liu

Reputation: 61

Linking issues with Boost.Python with g++

I am working on writing a wrapper around C++ functions to use in Python. Thus, I am trying to use Boost.Python as an experiment first. Below are the function I want to wrap:

hello_exp.cpp:

char const* greet()
{
   return "hello, world!";
}

#include <boost/python.hpp>

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

my Makefile:

COMPILER = g++
CPPFLAGS  = -g -Wall -std=c++11 -stdlib=libc++

# Python and BoostPython links.
BOOSTHEADERS = -I/usr/local/Cellar/boost/1.64.0_1/include/boost/
BOOSTLIBRARIES = -L/usr/local/Cellar/boost-python/1.64.0/lib/
BOOSTLIB = -lboost_python

PYTHONHEADERS = -I/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/include/python3.6m
PYTHONLIBRARIES = -L/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib
PYTHONLIB = -lpython3.6

# Collect links.
LIBRARIES = $(BOOSTLIBRARIES) $(PYTHONLIBRARIES) $(PYTHONLIB) $(BOOSTLIB)
HEADERS = $(BOOSTHEADERS) $(PYTHONHEADERS)

# Build target.
TARGET = hello_ext


# BEGIN MAKE
all: $(TARGET)

$(TARGET): $(TARGET).cpp
    $(COMPILER) -shared $(TARGET).cpp $(LIBRARIES) $(HEADERS) -o $(TARGET).so

clean:
    $(RM) $(TARGET)

However, after some experiments, I am perpetually stuck at this error...:

Undefined symbols for architecture x86_64:
  "boost::python::detail::init_module(PyModuleDef&, void (*)())", referenced from:
      _PyInit_hello_ext in hello_ext-476eb2.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [hello_ext.so] Error 1

So I have a installed python3 through HomeBrew, as well as boost and boost-python. Note that I actually installed the boost-python library without python2 support and only with python3 support.

Thank you in advance!

Upvotes: 1

Views: 903

Answers (1)

Z. Liu
Z. Liu

Reputation: 61

After some fixing and digging around, it turns out the problem is that the boost-python library I installed is still in python2. so instead, make sure you do

brew rm boost-python
brew install boost-python --with-python3 --without-python

to get the right version. Then the make file is just change

BOOSTLIB = -lboost_python

to

BOOSTLIB = -lboost_python3

And then just hit make :)

Upvotes: 1

Related Questions