1

Let's say:

foo.h:

struct foo {
    int bar();
};

foo.cpp:

#include "foo.h"

inline int foo::bar() {return 0;}

example.cpp:

#include "foo.h"
#include <iostream>

int main() {
    foo lol;
    std::cout << lol.bar() << std::endl;

    return 0;
}

Compiled with g++ -std=c++20 example.cpp foo.cpp -o example gives foo::bar() symbols not found.

In the book C++ Primer 5e at Ch.7.3 p.272 - 273, the authors say that it is possible to declare a class member function first and 'can be made inline later' in the definition. That is:

class Screen {
    // ...
    Screen &move(pos r, pos c); // can be made inline later
}
inline // we can specify inline on the definition
Screen &Screen::move(pos r, pos c) {
    // ...
}

Have I put the inline definition in foo.cpp in foo.h and only compile example.cpp the linker of course does not complain. But what is the problem here?

luma
  • 79
  • 1
  • 7
  • The inline method should be implemented in the header file (even if done after the class definition), not cpp (so that the compiler will find it for inlining when compiling other translation units). – wohlstad Aug 12 '22 at 04:45
  • [The definition of an inline function ... must be reachable in the translation unit where it is accessed](https://en.cppreference.com/w/cpp/language/inline) – Avi Berger Aug 12 '22 at 04:47
  • See [dupe](https://stackoverflow.com/questions/9370493/inline-function-members-inside-a-class#comment11834330_9370717) : *"You can't put the the inline method in the .cpp file. It still has to go in a header"* – Jason Aug 12 '22 at 04:49
  • Is it because the compiler must see the definition of an inline function in each translation unit? If so, i get it;D Thank you guys – luma Aug 12 '22 at 04:50

0 Answers0