开发者

Problem with linking, c++ member function to C callback

开发者 https://www.devze.com 2023-01-18 09:38 出处:网络
I\'m trying to interface a c++ member function with a legacy C library taking a function pointer - I can\'t see why this keeps coming up with link errors, Can anyone see why ?

I'm trying to interface a c++ member function with a legacy C library taking a function pointer - I can't see why this keeps coming up with link errors, Can anyone see why ?

link errors

/tmp/ccl2HY1E.o: In function `VerifyWrapper::verifyGlue(int)': callback.cpp:(.text._ZN13VerifyWrapper10verifyGlueEi[VerifyWrapper::verifyGlue(int)]+0xe): undefined reference to `VerifyWrapper::vfy'
/tmp/ccl2HY1E.o: In function `VerifyWra开发者_开发技巧pper::set(Verify&)': callback.cpp:(.text._ZN13VerifyWrapper3setER6Verify[VerifyWrapper::set(Verify&)]+0xf): undefined reference to `VerifyWrapper::vfy'

compile with: g++ callback.cpp -o callback

#include <iostream>
using namespace std;

class Verify
{
public:
    int verify(int i) { return i * 2; };
};


class VerifyWrapper
{
public:
    static int verifyGlue(int i) { return vfy->verify(i); };
    static void set(Verify& v) { vfy = &v;};
private:
    static Verify* vfy;
};


// legacy function
int func(int i, int(*f)(int))
{
int ret = f(i);
return ret;
}

int main(void)
{
int i = 10;
Verify v;
VerifyWrapper::set(v);
int ret = func(10, &VerifyWrapper::verifyGlue);
cout << "result : " << ret << endl;

return 0;
}


static Verify* vfy;

You need to define this static member, the declaration [that you have provided] is just not enough. The code won't pass the linker because the definition [of the static member] is missing.

Define vfy outside the class.

Verify* VerifyWrapper::vfy; //definition


You have only declared your static member. You also need to define it. In your .cpp/.cc file add the definition.

Verify* VerifyWrapper::vfy;
0

精彩评论

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