使用g ++

时间:2017-07-24 15:44:22

标签: python c++ boost linker-errors boost-python

我正在编写一个围绕C ++函数的包装器,以便在Python中使用。因此,我首先尝试使用Boost.Python作为实验。以下是我想要包装的功能:

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);
}

我的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)

然而,经过一些实验,我一直坚持这个错误...:

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

所以我通过HomeBrew安装了python3,以及boost和boost-python。请注意,我实际上安装了boost-python库而没有python2支持,只支持python3。

提前谢谢!

1 个答案:

答案 0 :(得分:1)

经过一些修复和挖掘后,问题是我安装的boost-python库仍然在python2中。所以相反,确保你做

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

获得正确的版本。然后make文件只是改变

BOOSTLIB = -lboost_python

BOOSTLIB = -lboost_python3

然后点击make:)