Multiple definition error at the linking stage

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?

Upvotes: 0

Views: 101

Answers (1)

Zig Razor
Zig Razor

Reputation: 3525

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.

Upvotes: 1

Related Questions