Compilation error

Hi Guys!
I can’t compile a project.

main.cpp

#include <Arduino.h>

#include <EEPROM.h>

#include "connection.h"

Connection connection;

void setup()

{

Serial.begin(9600);

connection.setTest(1);

}

void loop()

{

// put your main code here, to run repeatedly:

Serial.println(connection.getTest());

delay(1000);

}

connection.cpp

class Connection
{
private:
    int test;

public:
    void setTest(int val)
    {
        test = 1;
    }

    int getTest()
    {
        return test;
    }
};

connection.h

#ifndef CONNECTION_H
#define CONNECTION_H
class Connection
{
private:
    int test;

public:
    void setTest(int val);
    int getTest();
};
#endif // CONNECTION_H

platformio.ini

[env:nodemcuv2]

platform = espressif8266

board = nodemcuv2

framework = arduino

upload_speed = 115200

error

Linking .pio\build\nodemcuv2\firmware.elf
c:/users/zzz/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\nodemcuv2\src\main.cpp.o:(.text.setup+0xc): undefined reference to `Connection::setTest(int)'
c:/users/zzz/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\nodemcuv2\src\main.cpp.o: in function `setup':
main.cpp:(.text.setup+0x3a): undefined reference to `Connection::setTest(int)'
c:/users/zzz/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\nodemcuv2\src\main.cpp.o:(.text.loop+0x0): undefined reference to `Connection::getTest()'
c:/users/zzz/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\nodemcuv2\src\main.cpp.o:(.text.loop+0xd): undefined reference to `Connection::getTest()'
collect2.exe: error: ld returned 1 exit status
*** [.pio\build\nodemcuv2\firmware.elf] Error 1

Can somebody help?

Your connection.cpp is wrong. You’re redeclaring a class (the same as in connection.h) but then you implement the functions of it. Together with the connection.h you have a double declaration and the compiler gets confused… Write connection.cpp like this:

#include <connection.h>

void Connection::setTest(int val)
{
	test = 1; //note by me: it's unclear here why you don't assign val
}

int Connection::getTest()
{
	return test;
}

See reference

You can btw also do it as a header-only implementation. For that, delete connection.cpp and write conection.h as

#ifndef CONNECTION_H
#define CONNECTION_H
class Connection
{
private:
    int test;

public:
    void setTest(int val) {
    	test = 1;
    }
    int getTest() {
    	return test;
    }

};
#endif // CONNECTION_H

However, the header-and-source-file way is way cleaner and doesn’t require pulling in the entire code when the header is included. You should prefer the first way.

2 Likes