[solved] Can't compile project with multiple files - undefined reference

Hello there! Sorry if this is newbie question but I’ve not been able to find a solution that works for me when searching a lot on this issue.

I have an Arduino project that I’m now going to split into multiple class files to improve the structure. However, when I try to compile I get the famous “undefined reference to '…” error.

To make this as short as possible I’ve created a new d1_mini Arduino project from scratch in PlatformIO on Visual Studio Code. Using the IDE (right click/“new file”) I’ve added to files to the src folder; SlowPinPWM.h and SlowPinPWM.cpp. The contents in the files are:

SlowPinPWM.h:

#ifndef SlowPinPWM_h
#define SlowPinPWM_h

#include “Arduino.h”

class SlowPinPWM
{
public:
SlowPinPWM(byte pinNumber);
void hello();
private:
};

#endif

SlowPinPWM.cpp:

#include “Arduino.h”
#include “SlowPinPWM.h”

SlowPinPWM::SlowPinPWM(byte pinNumber) {
}

void hello() {
Serial.println(“Hello”);
}

and finally main.cpp:

#include <Arduino.h>
#include “SlowPinPWM.h”

SlowPinPWM boiler(1);

void setup() {
boiler.hello();
}

void loop() {
}

I have not made any changes to platformio.ini, this is all:
[env:d1_mini]
platform = espressif8266
board = d1_mini
framework = arduino

When I compile I get:

Processing d1_mini (platform: espressif8266; board: d1_mini; framework: arduino)

Verbose mode can be enabled via -v, --verbose option
CONFIGURATION: Redirecting...
PLATFORM: Espressif 8266 > WeMos D1 R2 & mini
HARDWARE: ESP8266 80MHz 80KB RAM (4MB Flash)
Library Dependency Finder → Library Dependency Finder (LDF) — PlatformIO latest documentation
LDF MODES: FINDER(chain) COMPATIBILITY(soft)
Collected 36 compatible libraries
Scanning dependencies…
No dependencies
Linking .pioenvs\d1_mini\firmware.elf
.pioenvs\d1_mini\src\main.cpp.o:(.text.setup+0x4): undefined reference to SlowPinPWM::hello()'** **.pioenvs\d1_mini\src\main.cpp.o: In function setup’:
main.cpp:(.text.setup+0x10): undefined reference to `SlowPinPWM::hello()’
collect2.exe: error: ld returned 1 exit status
*** [.pioenvs\d1_mini\firmware.elf] Error 1
========================================= [ERROR] Took 2.53 seconds =========================================
The terminal process terminated with exit code: 1

I’ve tried to add library and build options in platformio.ini but nothing helps. What am I doing wrong?

Best regards,
Per

You are implementing a method of a class here.

class SlowPinPWM
{
public:
SlowPinPWM(byte pinNumber);
void hello();
private:
};

So it must include the class name as:

void SlowPinPWM::hello()  {
   Serial.println("Hello");
}

If you want this function to be global then don’t declare it inside the class.

1 Like

How embarrassing. :sweat: Thanks a lot! :grinning: