Сompile code error: “undefined Reference to `Num::getNum()`

I create simple sketch

#include "Num.h"
void setup() {
  DDRB |= (1 << 5);
  int b = num.getNum();
}

saved it to desktop. and in this folder I put two my files:

//Num.h
class Num
{
    public:
    int m_num;
    int getNum() const;
    Num()        : m_num(0){}
    Num(int);
};

and cpp

#include "Num.h"
    inline int Num::getNum() const { return m_num; }
    Num::Num(int a) { m_num = a; }

when try compile it I get undefined reference to `Num::getNum() const'

Please help me understand whats wrong?

The easier you make it to read and copy the code the more likely it is that you will get help

Please follow the advice given in the link below when posting code , use code tags and post the code here

but I posted code

Where is the file that contains the definition of Num::getNum()? You have the declaration in Num.h but without a file (typically Num.cpp) that contains the definition, the function is undefined.

You originally posted your incomplete code without code tags an only added them afterwards and it is still not complete

and cpp... <- after that you will find Num.cpp

I have posted complete code , 3 files. .ino, .h, .cpp

I have read, that inline definition should be in header... and its little be not convenient ...
usually when we need to edit a class. we open the cp file. but if the inline needs to be defined in the header file, then to edit the code, we will have to open two files :frowning:

is there way (somehow) to define inline func not in header ?

I challenge you to compile the sketch you have posted ie

#include "Num.h"
void setup() {
  DDRB |= (1 << 5);
  int b = num.getNum();
}

I get undefined reference to `Num::getNum() const'

What I was getting it was the lack of a loop() function

I never wrote that you should delete loop :wink:

I didn't delete loop(). It was never there !

In your code you have this line

  int b = num.getNum();

Where is the num object created ?

Moving the declaration from the .cpp to the .h works:

//Num.h
class Num
{
    public:
    int m_num;
    inline int getNum() const {return m_num;}
    Num()        : m_num(0){}
    Num(int);
};

It is not uncommon to define small functions inside the .h file and 'inline' functions tend to be small.

You can't have an 'inline' function in a separate compilation unit since the compiler has no way to inline it without seeing it.

1 Like