0

I have a dummy class in Display.h:

#include <iostream>
#include <string>

class Display {
public:
    Display(int w, int h, const std::string &title);
    ~Display();
};

In Display.cpp I have the following:

#include "Display.h"

inline Display::Display(int w, int h, const std::string &title) {
    std::cout << "DISPLAY CONSTRUCTED " << title << "\n";
}

inline Display::~Display() {
    std::cout << "DISPLAY DESTRUCTED\n";
}

And I call the thing in the following manner in main.cpp:

#include "Display.h"

int main(void)
{
    Display display(10, 10, "Display");
    return 0;
}

My compiler is complaining:

main.cpp:(.text+0x57): undefined reference to `Display::Display(int, int, std::_
_cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&
)'                                                                              
/usr/bin/ld: main.cpp:(.text+0x80): undefined reference to `Display::~Display()'
collect2: error: ld returned 1 exit status  

But if I delete inline specifiers in the header, everything works fine (with only one removed the respected function got compiled without whining). It does not make sense for me.

PS. I put it together with Cmake, so I thought my build was messing something up, but manual compilation ensues the same.

Anton Tretyakov
  • 303
  • 1
  • 9
  • 1
    If I'm not mistaken, you can't inline between compilation units. Since it's inline, there's no reference to it and no way to link a declaration to its definition. – Ted Klein Bergman Apr 14 '22 at 20:25
  • 3
    An `inline` like this should be in the *header file*. – Eljay Apr 14 '22 at 20:27
  • 1
    If you want to implement the functions as inline, the function implementation must be visible to every translation unit using it. `main.cpp` makes use of both the constructor and the destructor, but it doesn't see the impelementations of those functions; in fact it doesn't even know about those functions being inline and if it did, this would result in an compiler error, since no definition is visible... – fabian Apr 14 '22 at 20:41
  • Thank you guys for your help! Now it makes perfect sense. – Anton Tretyakov Apr 15 '22 at 09:37

0 Answers0