-1

I have a class that handles the serial comms for my program called "serial.h and serial.cpp". It has the following constructor:

#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...");
    }
}

I want to call this class in another and use its methods, so I do the following in a class called 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 = "GetRestartInfo\r\n";
    std::string strR;
    Ret = ser.Write(strW);
    int bytes;

    Ret = ser.Read(strR);
    if ((strR.compare("201-OK [GetRestartInfo]\r\n")) != 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;
}

However, when I do this, I get the following error:

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

My original plan was to create a serial object in my .h file like:

public:
    serial ser;

But that did not work either... I'm a bit stumped as to how to do this, I know I'm probably missing something small. Any advice?

Kara
  • 6,115
  • 16
  • 50
  • 57
Cornel Verster
  • 1,664
  • 3
  • 27
  • 55
  • 1
    No, no... firstly if you use global variables you violate encapsulation rule. Secondly, where is declaration of serial class - this could be your problem. Finally, please refactor your code and try to use OOP rules: http://stackoverflow.com/questions/399656/are-there-any-rules-for-oop – LukeCodeBaker Aug 21 '13 at 08:57
  • You should at least include the headers in question. Or better provide an [SSCCE](http://sscce.org) – Arne Mertz Aug 21 '13 at 08:59
  • thanks, I will look into it, need to sharpen up on OOP – Cornel Verster Aug 21 '13 at 09:03

1 Answers1

0

What I ended up doing is creating an constructor with arguments:

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

Then I called it like so:

static serial ser(DEVICE_PORT, BAUD_RATE);

Works fine now. Thus, I am calling the serial object as a global variable!

Cornel Verster
  • 1,664
  • 3
  • 27
  • 55