用于python的C ++库 - 链接问题

时间:2011-12-11 20:13:02

标签: c++ python boost cmake

我编写了一个c ++库,我正在尝试使用boost :: python对它进行python绑定。这是文件的简化版本,我在其中定义它们:

#include <boost/python.hpp>
#include <matrix.h>
#include <string>

using namespace boost::python;

class MatrixForPython : public Matrix{
  public:
    MatrixForPython(int size) : Matrix(size) {}

    std::string hello(){
      return "this method works"; 
    }
};

BOOST_PYTHON_MODULE(matrix){
  class_<MatrixForPython>("Matrix", init<int>())
    .def("hello", &MatrixForPython::hello); 
}

编译由CMake完成,这是我的CMakeLists.txt:

project(SomeProject)
cmake_minimum_required(VERSION 2.8)

# find and include boost library
find_package(Boost COMPONENTS python REQUIRED)
find_package(PythonLibs REQUIRED)
include_directories(${PYTHON_INCLUDE_PATH})
include_directories(${Boost_INCLUDE_DIR})
include_directories(.)

# compile matrix manipulation library
add_library(matrix SHARED matrix.cpp python_bindings.cpp)
set_target_properties(matrix PROPERTIES PREFIX "")
target_link_libraries(matrix
  ${Boost_LIBRARIES} ${PYTHON_LIBRARIES})

编译完成没有错误,但是当我尝试运行简单的python脚本时:

import matrix

我收到以下错误

undefined symbol: _ZN6MatrixC2ERKS_

最令我困惑的事实是,当我改变MatrixForPython而不是从Matrix派生时,一切都按预期工作。为了使其有效,我应该改变什么?

编辑:matrix.h

#ifndef MATRIX_H_
#define MATRIX_H_

#include <boost/shared_array.hpp>


class Matrix{
  public:
    // creates size X size matrix
    Matrix(int size);

    // copy constructor
    Matrix(const Matrix& other);

    // standard arithmetic operators
    const Matrix operator * (const Matrix& other) const;
    const Matrix operator + (const Matrix& other) const;
    const Matrix operator - (const Matrix& other) const;

    // element manipulation
    inline void set(int row, int column, double value){
      m_data[row*m_size + column] = value;
    }

    inline double get(int row, int col) const{
      return m_data[row*m_size + col];
    }

    // norms
    double frobeniusNorm() const;
    double scaledFrobeniusNorm() const;
    double firstNorm() const;
    double infNorm() const;

    // entire array manipulation
    void zero();    // sets all elements to be 0
    void one();     // identity matrix
    void hermite(); // hermite matrix


    virtual ~Matrix();


    // less typing
    typedef boost::shared_array<double> MatrixData;

  private:
    int m_size; 
    MatrixData m_data;
};




#endif

1 个答案:

答案 0 :(得分:2)

  

未定义的符号:_ZN6MatrixC2ERKS_

这是因为您错过了共享库中的Matrix::Matrix(const Matrix&)复制构造函数:

samm@mac ~> echo _ZN6MatrixC2ERKS_ | c++filt 
Matrix::Matrix(Matrix const&)
samm@mac ~>