0

As I understand functions get included in .cc to avoid duplication of them as headers get included many times in different places. It is not clear if such overhead would occur for the function with empty body. Example of such function could be the virtual destructor.

Draif Kroneg
  • 743
  • 13
  • 34

2 Answers2

3

If you refer to free functions you should either:

  1. Mark them as inline
  2. Mark them as static
  3. Place them within an anon namespace

Note that in #2 and #3 the function is duplicated in each translation unit (you will have the same code duplicated every-time you include it)

If you are speaking about member functions of a class (inline hinted by default, though some people like to make it explicit, though this is just a hint) AFAIK they have external linkage, so you can be sure that you wont have the same function definition twice. In brief, it is fine.

Related: Are C++ class methods defined in the header always inlined?

Community
  • 1
  • 1
Mario Corchero
  • 5,257
  • 5
  • 33
  • 59
0

Functions are defined in a separate translation units for a few reasons:

  • The function needs to be only compiled in a single translation unit rather than in all of the translation units that use it †. I suppose this is the overhead that you mention.
  • The separation can be used to avoid circular dependencies between complicated functions.
  • Modifying the function in a single translation unit does not cause the others to be recompiled.

If you define the function in all translation units that use it, by defining it inline, then†† the optimizer can replace calls to the function with inline expansion. That is most preferable when the function is simple and called often from few places.

An empty function is sufficiently simple for inline expansion, so defining it inline is usually advantageous. It also can't have a problematic dependency that would need to be avoided. It would also have negligible overhead to compile it multiple times if that applies. If you know that it will remain empty, then it won't be changed and therefore won't cause massive recompiles.

In conclusion, defining an empty function inline is preferable. Unless you know that it will be modified later and want to avoid recompilation when that happens.

† A smart compiler may optimize the compilation by reusing compiled inline functions if multiple translation units are compiled at the same time thereby removing this overhead.

†† If a non-inline function is called from the same translation unit where it's defined, then it can be expanded inline too. Even the call is in another translation unit, the inline optimization can be done if the translation units are compiled at the same time. Even if not, link time optimization can allow inlining across translation units. Note that virtual functions cannot be expanded inline unless the runtime type of the object can be deduced at compile time.

eerorika
  • 232,697
  • 12
  • 197
  • 326