Search code examples
c++compiler-errorsarduinoarduino-ide

Compile a .cpp file for an Arduino project


I'm trying to start an Arduino project with Arduino IDE and I'd like to use external C++ code outside the .ino main file. In particular, I have the following file:

 arduino.ino <- main .ino file
 /HeartSensor
    HeartSensor.h
    HeartSensor.cpp
 /oledScreen
    oledScreen.h
    oledScreen.cpp

To import the two files in the folders I did the following:

 #include "HeartSensor/HeartSensor.h"
 #include "oledScreen/oledScreen.h"

The HeartSensor.h file, for example, contains the following code:

#ifndef HEARTSENSOR_H

#define WINDOWSIZE 50
#define HEARTSENSOR_H

#include <Arduino.h>

class HeartSensor{

private:
   float bpm = 0.0;
   int heartStatus = 0;
   bool receivingSignal = false;

   float ecgSignal[WINDOWSIZE];

public:

   // Constructors
   HeartSensor();
   ~HeartSensor();

   // Getters
   float getBPM(){ return bpm; };
   int getHeartStatus(){ return heartStatus; };
   bool getReceivingSignal(){ return receivingSignal; };

   // Setters
   void setBPM(const float& newBpm){ bpm = newBpm; };
   void setHeartStatus(const int& newHeartStatus){ heartStatus = newHeartStatus; };
   void setReceivingSignal(const bool& newReceivingSignal){ receivingSignal = newReceivingSignal; };

   void addSample(const float& newSample);

};

#endif

And the HeartSensor.cpp file contains the following code:

#include "HeartSensor.h"

HeartSensor::HeartSensor(){

}

void HeartSensor::addSample(const float& newSample){
   for(int i = 1; i < WINDOWSIZE-1; i++){
      ecgSignal[i-1] = ecgSignal[i];
}
   ecgSignal[WINDOWSIZE-1] = newSample;
}

If I try to access one the member functions in the header file, I have no problem. However, if I try to access a function that is in the cpp file like so:

HeartSensor* myHeartSensor;
myHeartSensor->addSample(0.0);

then the following error shows up:

arduino.ino:36: undefined reference to `HeartSensor::addSample(float const&)'
collect2: error: ld returned 1 exit status

Do you know how I can compile the cpp files?


Solution

  • Lay out your project as:

    arduino.ino <- main .ino file
    /src
      /HeartSensor
        HeartSensor.h
        HeartSensor.cpp
      /oledScreen
        oledScreen.h
        oledScreen.cpp
    

    To import the two files in the folders, do the following:

    #include "src/HeartSensor/HeartSensor.h"
    #include "src/oledScreen/oledScreen.h"