Undefined reference to `Class::Method()

Hi I am using platformio to develop some code for arduino.
I have been trying to use private libaries, using the lib folder, however I seem to always get an undefined reference error. Eg.

lib/TestLib/TestLib.cpp

#include <Arduino.h>

class Test {
public:
	void test() {
		Serial.print("Hi");
	};
};

lib/TestLib/TestLib.h

#pragma once

class Test {

public:

    void test();

};

now in src.main.cpp

#include <Arduino.h>

#include <TestLib.h>

Test a;

void setup() {

  Serial.begin(9600);

};

void loop() {

  Serial.print("IR Distance: ");

  a.test();

};

When I try to build I get the error

C:\Users<username>\AppData\Local\Temp\ccseYRvx.ltrans0.ltrans.o: In function main': <artificial>:(.text.startup+0x108): undefined reference to Test::test()’
collect2.exe: error: ld returned 1 exit status
*** [.pio\build\uno\firmware.elf] Error 1

Anyone know how to prevent this error from occuring

No. You’re implementing classes wrong. See https://www.learncpp.com/cpp-tutorial/class-code-and-header-files/.

The TestLib.h is fine but TestLib.cpp must be

#include <TestLib.h>
#include <Arduino.h>

void Test::test() {
   Serial.println("Hi"); //took liberty to change print to println
}

This is purely a C++ language problem you’re having, not anything with PlatformIO.

1 Like