c++linkerlinker-errorslnk2005inherited

C++ linker error when using same .h-file in inherited class


I have two classes: ClassA and ClassB. ClassB inherits the ClassA. There is a utility.h-header file included to both classa.cpp and classb.cpp so that I can use the method

round(double number, int precision)

from the utilities.h in both .cpp-files.

When using it in ClassA like this:

double roundANumber(double number, int precision)
{
    return Utilities::round(number, precision);
}

it works fine. But when I try to use it in the ClassB like this:

double roundAnotherNumber(double number, int precision)
{
    return Utilities::round(number, precision);
}

linker gives me error:

error LNK2005: "double __cdecl Utilities::round(double,int)" (?
round@hUtilities@@YANNH@Z) already defined in classa.obj

and I can't seem to find a reason why this is.

Thank you in advance.

Edit: Added that the Utilities.h only contains this

 #include <cmath>

 namespace MathUtilities {

 double round(double number, int precision) {
     int precisionFactor = std::pow(10, precision);
     return std::round(number * precisionFactor) / precisionFactor;
 }
 }

Solution

  • Headers are just parsed as if they were included directly. Thus, you end up duplicating the function definition.

    To fix this, use inline:

    inline double round(double number, int precision) {...}