对类::对象的未定义引用

Undefined reference to Class::Object

本文关键字:引用 未定义 对象 对类      更新时间:2023-10-16

我有一个类,它为我的程序处理串行命令,名为"serial.h和serial.cpp"。它有以下构造函数:

#include "serial.h"
serialib LS;
serial::serial(void)
{
    int Ret;
    Ret = LS.Open(DEVICE_PORT, BAUD_RATE);
    if (Ret != 1)
    {
        printf("Serial port open FAILED!n");
    }
    else
    {
        printf("Serial port successfully opened...");
    }
}

我想在另一个类中调用这个类并使用它的方法,所以我在一个名为dataHandler.cpp的类中执行以下操作:

#include "dataHandler.h"
#include "serial.h"
using namespace opendnp3;
serial ser;
dataHandler::dataHandler(void)
{
}

dataHandler::~dataHandler(void)
{
}
int dataHandler::sendRestartCommand()
{
    int Ret;
    char buffer[128];
    RestartInfo ri;
    std::string strW = "GetRestartInforn";
    std::string strR;
    Ret = ser.Write(strW);
    int bytes;
    Ret = ser.Read(strR);
    if ((strR.compare("201-OK [GetRestartInfo]rn")) != 0)
    {
        printf ("Wrong response from device to restart message.n");
        return 0;   
    }
    Ret = ser.Read(strR);
    std::string s_bytes = strR.substr(4,3);
    std::stringstream ss(s_bytes);
    if (!(ss >> bytes))
        bytes = 0;
    Ret = ser.Read(buffer);
    writeSettings(ri);
    return 1;
}

然而,当我这样做时,我会得到以下错误:

dataHandler.o: In function `dataHandler::sendRestartCommand()':
dataHandler.cpp:(.text+0x31c): undefined reference to `dataHandler::ser'
collect2: error: ld returned 1 exit status

我最初的计划是在.h文件中创建一个串行对象,比如:

public:
    serial ser;

但这也不起作用。。。我有点困惑于如何做到这一点,我知道我可能错过了一些小东西。有什么建议吗?

我最终做的是创建一个带有参数的构造函数:

serial::serial(std::string devPort, int baud)
{
    int Ret;
    const char * devP = devPort.c_str();
    Ret = LS.Open(devP, baud);
    if (Ret != 1)
    {
        printf("Serial port open FAILED!n");
    }
    else
    {
        printf("Serial port successfully opened...");
    }
}

然后我这样称呼它:

static serial ser(DEVICE_PORT, BAUD_RATE);

现在工作正常。因此,我将串行对象称为全局变量!