Serial pc Multiple defined

03 Mar 2011

Ok this is a C++ question,

How can I write to one serial port from a class and from main?

If i have main like this:

#include "mbed.h"
#include "hello_class.h"

int main() {
    hello_class myObj;
    myObj.hello();
}

hello_class.h

#include "mbed.h"
class hello_class {
public:
    void hello(); /* Declaration of the function */
};

And hello_class.cpp

#include "mbed.h"
#include "hello_class.h"
Serial pc( USBTX,USBRX );

void hello_class::hello () {
    pc.printf("\nHello World!\n");
}

This Works!

I can read Hello World! on serial

but how can i write something like this:

int main() {
    hello_class myObj;
    myObj.hello();
    
    pc.printf("\nHello From MAIN")  /* HELLO FROM MAIN */
}

is it posible or not???

03 Mar 2011

You could just tell main.cpp that there is a global pc object located in some other module like this:

#include "mbed.h"
#include "hello_class.h"

extern Serial pc;

int main() 
{
    hello_class myObj;
    myObj.hello();
    
    pc.printf("\nHello From MAIN");  /* HELLO FROM MAIN */
}

If this is the route that you go, you might want to define the pc object in main.cpp and add the extern to hello_world.cpp instead so that if you add other modules, they will all point back to the one defined by the main module.

Another method might be to have main.cpp create the Serial object and then pass a reference to the hello_class object when it is constructed. This wouldn't require any globals which you may or may not prefer.

main.cpp

#include "mbed.h"
#include "hello_class.h"

int main() 
{
    Serial      pc(USBTX, USBRX);
    hello_class myObj(pc);
    
    myObj.hello();
    
    pc.printf("\nHello From MAIN");  /* HELLO FROM MAIN */
}

hello_class.h

class hello_class 
{
public:
    hello_class(Serial& serialObject);
    void hello(); /* Declaration of the function */
protected:
    Serial& pc;
};

hello_class.cpp

#include "mbed.h"
#include "hello_class.h"

hello_class::hello_class(Serial& serialObject) : pc(serialObject)
{
}

void hello_class::hello () 
{
    pc.printf("\nHello World!\n");
}
03 Mar 2011

Thank you, for the info. I already try pass the Serial as an Argument and it didn't work, then it occur to me pass it as a reference but it was late an I didn't try it out.

Thanks again Ernesto.