简体   繁体   中英

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;
 }
 }

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) {...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM