views:

112

answers:

2

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 `VerifyWrapper::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;
}
+5  A: 

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
Prasoon Saurav
thanks very much!
Stonky
@Stonky : If you are satisfied with my answer you can upvote it and accept it by clicking on the checkmark [next to my answer] `;)`
Prasoon Saurav
i will - apparantly i can't do if for another 6 minutes though.
Stonky
+1  A: 

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

Verify* VerifyWrapper::vfy;
m-sharp