I have a task:
To implement a template vector class (let’s name it myvector). I need to use this class in multiple files in my project, so I’ve put it’s declarations in “myvector.h” file, and implementation into “myvector.hpp” file, and then included “myvector.hpp” in “myvector.h” after all the declarations (as described there). However, I have one non-template function in “myvector.hpp”. So when I include “myvector.h” file in main file, everything works fine. But when I include “myvector.h” in another one file (“bignum.cpp”), I get a linker error:
error LNK2005: "unsigned int __cdecl gerasimov_dmitry::calculate_capacity(unsigned int)" (?calculate_capacity@gerasimov_dmitry@@YAII@Z) already defined in bignum.obj
I understand the causes – “bignum.h” code gets included both in main.cpp and in bignum.cpp file, so compiler doesn’t know which one “calculate_capacity” function to use. So, my question is how to fix this situation.
You have to declare the function
inline(or alternatively move the definition to a single translation unit).The problem that you are facing is that if you define the function in the header, and include that header in more than one translation unit, the compiler will generate the function in all translation units.
When the linker tries to generate the program (or library) it finds that the function is defined multiple times and complains about it, as that is a violation of the ODR (One Definition Rule). By marking the function as
inlinethe compiler will flag that function so that when the linker sees the multiple definitions instead of choking it will discard all but one of the definitions.