Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
9 years, 2 months ago.
Compiler error using pc.printf function in a class method - definition error somewhere?
I declare an instance of the serial class in main:-
Serial pc(USBTX, USBRX);
Then in library SerialCommand.cpp, in the addCommand method, I output data over the serial port using pc if SERIALCOMMAND_DEBUG is defined (which in this case it is):
void SerialCommand::addCommand(const char *command, void (*function)()) { #ifdef SERIALCOMMAND_DEBUG pc.printf("Adding command ("); pc.printf(commandCount); pc.printf("): "); pc.println(command); #endif
This generates the followinging error from the compiler:
Error: Identifier "pc" is undefined in "mSerialCommand/mSerialCommand.cpp", Line: 50, Col: 6
pc has been defined in main, but can't be found by addCommand....how do I make pc visible to addCommand?
I feel that this must be something very basic, but can't seem to reference my intial definition of pc. Any thoughts? Jimgi
1 Answer
9 years, 2 months ago.
You tell the compiler that it is defined external to that file by adding a line to mSerialCommand.cpp:
extern Serial pc;
That will tell the compiler that a serial port called pc is defined as a global elsewhere.
The compiler treats each .cpp file as a completely independent entity that knows nothing about the contents of other .cpp files.
If you want to use the same globals in multiple files it's normal to put the extern lines into a .h header file that you can then include in everything, that way all of the globals are listed in one place and there is no danger of getting different spellings in different files etc...
thanks Andy, I did this, and it doesn't seem to understand Serial: Error: Identifier "Serial" is undefined in "mSerialCommand/mSerialCommand.cpp", Line: 26, Col: 11
#include "mSerialCommand.h" extern Serial pc; /** * Constructor makes sure some things are set. */ SerialCommand::SerialCommand() : commandList(NULL), commandCount(0),
You also need to include mbed.h otherwise it doesn't know what a Serial is.
Both the mbed include and the extern could go in mSerialCommand.h instead if you wanted
posted by 15 Sep 2015Yup! That did it - thanks for the help Andy. I assumed that because main.cpp included the mbed.h file, that it was enough!
The library is a re-write of the Arduino SerialCommand library for the mbed. Pretty much works now - this was just the last bit to include the debug switch. I gave up on the RPC library.... Jimgi
posted by 15 Sep 2015You can also just use printf without the pc part, then you also don't need to use the extern part.
posted by 15 Sep 2015