c++ - 链接器错误 : undefined symbol

标签 c++ makefile linker boost-python

我想做什么

我正在尝试创建 2 个 C++ 类。

  • 一个,名为 Agent,将作为类 2 的成员实现
  • 两个,名为 Env,将通过 boost.python 暴露给 Python(尽管我怀疑这个细节对我的问题无关紧要)

问题

在使用我的 make 文件成功编译后,我尝试运行我的 python 脚本,但我在我的扩展模块(c++ 代码)上收到一个导入错误,显示为“ undefined symbol :_ZN5AgentC1Effff”。除了所有 boost-python 的东西,我认为这是一个简单的 C++ 链接器错误。

这是我的文件:

Agent.h

class Agent {
public:
    float xy_pos[2];
    float xy_vel[2];
    float yaw;
    float z_pos;
    Agent(float x_pos, float y_pos, float yaw, float z_pos);

};

Agent.cpp

#include "Agent.h"
Agent::Agent(float x_pos, float y_pos, float yaw, float z_pos)
{
   xy_vel[0] = 0;
   xy_vel[1] = 0;
   xy_pos[0] = x_pos;
   xy_pos[1] = y_pos;
   z_pos = z_pos;
   yaw = yaw;
};

test_ext.cpp(我的 Env 类所在的位置)

#include "Agent.h"
#include <boost/python.hpp>
class Env{
    public: 
        Agent * agent;
        //some other members
        Env() {
            agent = new Agent(13, 10, 0, 2);
        }
        np::ndarray get_agent_vel() {
        return np::from_data(agent->xy_vel, np::dtype::get_builtin<float>(),
                                 p::make_tuple(2),
                                 p::make_tuple(sizeof(float)),
                                 p::object());
         }
         void set_agent_vel(np::ndarray vel) {
             agent->xy_vel[0] = p::extract<float>(vel[0]);
             agent->xy_vel[1] = p::extract<float>(vel[1]);
         }
}

BOOST_PYTHON_MODULE(test_ext) {
    using namespace boost::python;
    class_<Env>("Env")
    .def("set_agent_vel", &Env::set_agent_vel)
    .def("get_agent_vel", &Env::get_agent_vel)
}

生成文件

PYTHON_VERSION = 3.5

PYTHON_INCLUDE = /usr/include/python$(PYTHON_VERSION)

# location of the Boost Python include files and library

BOOST_INC = /usr/local/include/boost_1_66_0

BOOST_LIB = /usr/local/include/boost_1_66_0/stage/lib/

# compile mesh classes

TARGET = test_ext

CFLAGS = --std=c++11

$(TARGET).so: $(TARGET).o

    g++ -shared -Wl,--export-dynamic $(TARGET).o -L$(BOOST_LIB) -lboost_python3 -lboost_numpy3 -L/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu -lpython3.5 -o $(TARGET).so


$(TARGET).o: $(TARGET).cpp Agent.o

    g++ -I$(PYTHON_INCLUDE) -I$(BOOST_INC) -fPIC -c $(TARGET).cpp $(CFLAGS)

Agent.o: Agent.cpp Agent.h

    g++ -c -Wall Agent.cpp $(CFLAGS)

最佳答案

你永远不会在任何地方链接到 Agent.o

首先,您需要像构建 test_ext.o 一样使用相同的标志来构建它。然后,您需要在创建共享库时实际链接到 Agent.o

关于c++ - 链接器错误 : undefined symbol,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49843412/

相关文章:

c++ - 使用 clang 显式 C++ 模板实例化

DirectX SDK 的 C++ 链接器错误

c++ - 树向量化 : gcc optimization flag

c++ - C2440 无法在 C++ WinApi 中将 LRESULT 转换为 WNDPROC

c++ - ceil() 函数的意外结果

c++ - c++中的多个三元运算符

c - 如何修复在 Dev C 和 Netbeans 中有效但在 Eclipse 中无效的 makefile?

c++ - 如何使用 Jam make 工具构建项目的不同版本?

java - 创建多个文件用java循环并存储在驱动器中,如何?

c++ - 与 cmake 链接错误