0

As a followup to the question Should I define static inline methods in header file?

If I have two helper functions in two separate cpp files have the same signature, the compiler will complain about ODR. Is it therefore good style to make free functions in a cpp file static to avoid name clashes and give the linker less work?

More generally asked: What are advantages and disadvantages of making free functions inline, static or static inline in a cpp file?

Fabian
  • 4,001
  • 4
  • 28
  • 59
  • If the function is only meant to be used in that one cpp file there is no disadvantage to making it static, AFAIK. – super May 14 '20 at 06:42
  • One disadvantage of `static` in a header file is possible binary bloat. – Evg May 14 '20 at 07:15
  • I have a few clarifying questions for your scenario: `A.cpp` contains a free function `int foo(string s)`, at the same time `B.cpp` also contains a free function `int foo(string s)`. Are the two `foo`s identical, or do they have different implementations? If they are identical, is that by chance and subject to possible divergence, or do you want/require them to always be the same? – Frodyne May 14 '20 at 07:28
  • The two `foo`s are independent of each other and different. If they were the same, I should of course put them into one common header. – Fabian May 14 '20 at 08:37
  • I thought so but wanted to be sure. Now I am certain that @Bathsheba's answer is what you are looking for. An anonymous namespace gives complete containment within the translation unit (TU), it can also contain other stuff that you don't want "leak" out of the TU (internal types, classes, and so on), and you don't have to worry about binary bloat since the function isn't shared between TUs (and now literally cannot). – Frodyne May 14 '20 at 09:49

1 Answers1

5

It's good practice to use an anonymous namespace for such a function:

namespace {
    // your function here; no need for static or inline
}

In this way it's confined solely to that translation unit, not visible to the linker, and so the one definition rule will hold.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483