开发者

gtest problem with inline function

开发者 https://www.devze.com 2023-03-02 03:50 出处:网络
hello i have which include inline function开发者_JAVA百科, when i try testing this class with google test, i have error like:

hello i have which include inline function开发者_JAVA百科, when i try testing this class with google test, i have error like:

 error LNK2019: unresolved external symbol "public: double __thiscall Math::returnPi(void)" (?returnPi@Math@@QAENXZ) referenced in function "private: virtual void __thiscall Speed_Math_Test::TestBody(void)" (?TestBody@Speed_Math_Test@@EAEXXZ)

for example my class(header file)

class Math
{
public:
    Math(void);
    inline double returnPi();
    ~Math(void);
};

my class(cpp file)

Math::Math(void)
{}
Math::~Math(void)
{}
double Math::returnPi()
{ return 3.14;}

test:

TEST(EQ, Math)
{
    Math *m=new Math();
    EXPECT_EQ(3.14,m->returnPi());
}

what i need to do? i read manual but dont see how i can resolved this error.


An inline function should be in your header file, not in your source file so it can actually be inlined by the callers (which don't have access to the source file).

Moreover, you don't need to specify inline in your class declaration if you give the definition of the function.

So your header should become:

class Math
{
public:
    Math(void);
    double returnPi() { return 3.14; } // no need to specify inline here
    ~Math(void);
};

And remove the definition for returnPi() from your source file.

Note that you could also have done:

class Math
{
public:
    Math(void);
    double returnPi();
    ~Math(void);
};


inline double Math::returnPi() { return 3.14; } // inline is mandatory here to avoid respecting the "One Definition Rule"

The second solution is good if you want to keep the class declaration separate from the function definition.

Also note that inline does not guarantees that the actual function calls will be inlined: the only thing it enforces is that you don't have to respect the "One Definition Rule": the inline function must have the same definition in all translation units.


Are you sure you are compiling the class' CPP file as part of the project? This should be fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消