2

I have two friend functions in a class in a header file

both of them are declared in the class

but the problem is when I write their body in a .cpp file I get this error

undefined reference to...

and when I write the body in the .h file I get this error

multiple definition of..

so I don't understand where should I write the body of friend function?

Raea6789
  • 141
  • 1
  • 11

1 Answers1

5

where should friend functions be written?

Same as member functions. Either inline in the header, or non-inline in a single translation unit. If inline, it can be outside or inside the class definition. If outside, then it must be declared inline explicitly.

I get this error

undefined reference to...

See this: What is an undefined reference/unresolved external symbol error and how do I fix it?

and when I write the body in the .h file I get this error

multiple definition of..

This means that you failed to declare the function as inline, and consequently failed to follow the One Definition Rule. Solution is to declare the function inline.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • 1
    This kinda makes my answer less useful, so here's the one significant difference: [A link to documentation on the One Definition Rule](https://en.cppreference.com/w/cpp/language/definition) – user4581301 Jun 25 '20 at 15:22