0

If my projects consist of two translation units a.cpp and b.cpp, and there is h.cpp that have a function definition. In this case, each .cpp file will be successfully compiled, but we will get multiple definitions at the linking stage. To avoid this (if you don’t put the definition in a separate .cpp file), you can make this function

  1. inline
  2. static
  3. static inline
  4. surround it with an empty namespace

Can someone explain the difference between these four approaches, which is better to use. And what will happen if it is an template function, will there be any problems?

  • All options being considered by you are useful in exceptional scenarios when you include header file containing function *definitions*. Usually you keep only *declarations* in headers and include those in cpp files and keep definitions in one of the cpp file or in a separate cpp file. – Mohit Jain Feb 09 '20 at 15:01

1 Answers1

1

These are useful explanation of your first 3 declaration:

  1. inline
  2. static
  3. static inline

The fourth option is a special case to study in some circumstances.

In case of Template you have to remember that all the function have to been defined in the same file, often a .h or .hpp . If you want to separate definition from implementation remember to include you .cpp or the file in which the function are implemented at the end of the file where the function are defined.

Zig Razor
  • 3,381
  • 2
  • 15
  • 35