I'm having trouble creating a static object. Take a look at this snippet from a header file...
#include <stdlib.h> #include "WProgram.h"
#include "Logger.h" // this file
#include <PrivateLogger.h>
class Logger
{
public:
Logger(); // Constructor
void writeLine(char * line); // Write a line of data to the log file
void close(); // Close the file
private:
// Member variables
PrivateLogger m_logger;
};
This code currently works as shown. It will compile and run without problems. As soon as I try to make my object static like this.....
private:
// Member variables
static PrivateLogger m_logger;
Then I get the follwoing error
Logger\Logger.cpp.o: In function
Logger::close()': C:\all_apps\arduino-0021\libraries\Logger/Logger.cpp:57: undefined reference to
Logger::m_logger'
C:\all_apps\arduino-0021\libraries\Logger/Logger.cpp:57: undefined reference toLogger::m_logger' Logger\Logger.cpp.o: In function
Logger::writeLine(char*)':
C:\all_apps\arduino-0021\libraries\Logger/Logger.cpp:50: undefined reference toLogger::m_logger' C:\all_apps\arduino-0021\libraries\Logger/Logger.cpp:50: undefined reference to
Logger::m_logger'
The code it's actually complaining about is listed here....
// Constructor
Logger::Logger()
{
}
void Logger::writeLine(char * line) // Write a line of data to the log file
{
m_logger.writeLine(line);
}
void Logger::close()
{
m_logger.close();
}
My Logger object is going to be used within lots of different classes within my sketch, so I'm trying to use the static keyword to force only a single instance of the logger class.
I'm trying to do this for two reasons, firstly since I only have one SD card and one log file it makes sense to only have a single object accessing it and, although it is possible to have multiple objects writing to the same file, whichever object closes the file first (and thus 'commits' whatever it's written) get to overwrite anything that any other object was writting.
Basically I have a couple of questions....
- is it possible to implement a singleton class in arduino? If so, how?
- Is my approach correct or not? and if it is why isn't it working and how do I fix it?
Cheers
Mike