Let me preface this by saying I'm coming from a Java background, so please forgive me if I've made some stupid mistake here....
I'm writing a C++ library that I would like to make compatible with both Arduino as well as the RaspberryPi. Most of the code is just clean, standard C++, but a few functions are hardware-specific (GPIO calls, for instance). Being from a Java background, I thought, I'll just create a HAL interface that defines those hardware-specific functions, and then I can create implementations of that interface for the RPi and Arduino, only to find out that interfaces are not a thing in C++ and you have to use virtual methods instead. Please see the bottom of my question for my source files.
However, when I went to actually use this, I discovered something quite strange: using the HAL on the heap compiles, but using it on the stack does not
//THIS DOES NOT COMPILE
MyLibraryHAL hal = HAL_RaspberryPi();
hal.someHwSpecificFunction(65);
//BUT THIS DOES
MyLibraryHAL* hal = new HAL_RaspberryPi();
hal->someHwSpecificFunction(65);
The error is:
src.ino:67: undefined reference to MyLibraryHAL::someHwSpecificFunction(unsigned char)
.
Why is this? Is this just a feature of how virtual methods work? Or is there some concept I'm missing here?
MyLibraryHAL.h
#include <stdint.h>
#ifndef MyLibraryHAL_h
#define MyLibraryHAL_h
class MyLibraryHAL
{
public:
virtual void someHwSpecificFunction(uint8_t param);
};
#endif
HAL_Arduino.h
#include <stdint.h>
#include "MyLibraryHAL.h"
#ifndef HAL_Arduino_h
#define HAL_Arduino_h
class HAL_Arduino : public MyLibraryHAL
{
public:
void someHwSpecificFunction(uint8_t param);
};
#endif
HAL_Arduino.cpp
#include <stdint.h>
#include "HAL_Arduino.h"
void HAL_Arduino::someHwSpecificFunction(uint8_t param)
{
//do things
}
HAL_RaspberryPi.h
#include <stdint.h>
#include "MyLibraryHAL.h"
#ifndef HAL_RaspberryPi_h
#define HAL_RapsberryPi_h
class HAL_RaspberryPi : public MyLibraryHAL
{
public:
void someHwSpecificFunction(uint8_t param);
};
#endif
HAL_RaspberryPi.cpp
#include <stdint.h>
#include "HAL_RaspberryPi.h"
void HAL_RaspberryPi::someHwSpecificFunction(uint8_t param)
{
//do things
}