undefined reference when using custom class

Hi,

I have tried to solve this myself, but cannot figure it out. I had my own class working fine, when in the main ino file. When I move it to it's own class, the error below appears.

test.ino

#include <OneWire.h>
#include <DallasTemperature.h>
#include "./SensorTemperature/SensorTemperature.h"

SensorTemperature mr_grumpy_objects[] = { 25 };
void setup() {
  Serial.begin(115200);
}

void loop() {
  Serial.println("Wait 5000ms...");
  
  delay(5000); 
}

./SensorTemperature/SensorTemperature.h

#ifndef SensorTemperature_h
#define SensorTemperature_h

#include "Arduino.h"
#include <OneWire.h>
#include <DallasTemperature.h>

class SensorTemperature {
    public:
        SensorTemperature(byte pin);

    private:
        byte _pin;
        OneWire _oneWire;
        DallasTemperature _sensors;
};

#endif

./SensorTemperature/SensorTemperature.cpp

#include "Arduino.h"
#include "SensorTemperature.h"

#include <OneWire.h>
#include <DallasTemperature.h>

SensorTemperature::SensorTemperature(byte pin): _oneWire( pin ), _sensors( &_oneWire ) {
    _pin = pin;
    _sensors.begin();      
};

When I compile, I get the following error:

Loading configuration...
Initializing packages...
Preparing boards...
Verifying...
sketch\test.ino.cpp.o:(.literal.startup._GLOBAL__sub_I_mr_grumpy_objects+0x8): undefined reference to `SensorTemperature::SensorTemperature(unsigned char)'

sketch\test.ino.cpp.o: In function `_GLOBAL__sub_I_mr_grumpy_objects':

d:\test/test.ino:17: undefined reference to `SensorTemperature::SensorTemperature(unsigned char)'

collect2.exe: error: ld returned 1 exit status

exit status 1
[Error] Exit with code=1

If I move the .h and .cpp file into d:\test and remove the path in the test.ino header include, it compiles and works fine.

Is there really no way to organise your classes into a directory structure? I do not want to import the class in as a library. I want to organise my code with separate class files.

I think there are limitations to what .cpp files the IDE will find and compile. I suspect it will work if you move your SensorTemperature library to the Arduino/libraries folder OR you put the files in a subdirectory named 'src' or 'util'.

Bingo! :slight_smile:

That worked a treat and it's even recursive.

From:

#include "SensorTemperature.h"

To:

#include "src/classes/SensorTemperature/SensorTemperature.h"

Many thanks!