Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined reference to static function pointer member in c++, what am I doing wrong?

please consider these files:

p.h:

#ifndef _p_h_
#define _p_h_

class p{
public:    
    static void set_func(int(*)());

private:
    static int (*sf)();

};
#endif

p.cpp:

#include "p.h"
#include <cstdio>

int (p::*sf)() = NULL;    //defining the function pointer

void p::set_func(int(*f)()){
    sf = f;
}

main.cpp:

#include "p.h"
#include <iostream>

int function_x(){
        std::cout << "I'm function_x()" << std::endl;
        return 1234;
}

int main(){
        p::set_func(function_x);
}

when compiling, I get this:

$ g++ -o pp main.cpp p.cpp
/tmp/ccIs0M7r.o:p.cpp:(.text+0x7): undefined reference to `p::sf'
collect2: ld returned 1 exit status

but:

$ g++ -c -o pp p.cpp

compiles right.

What's wrong with the code? I just can't find where the problem is, please your help will be more than appreciated.

Thanks.

like image 401
Auxorro Avatar asked Oct 20 '11 17:10

Auxorro


1 Answers

Your attempt at defining p::sf is incorrect – yours is a definition of a global variable named sf that is of type int (p::*)(), i.e. a pointer to a member function. Consequently p::sf remains undefined, hence the linker error.

Try this instead:

int (*p::sf)() = 0;

// or,

typedef int (*p_sf_t)();
p_sf_t p::sf = 0;
like image 80
ildjarn Avatar answered Oct 01 '22 21:10

ildjarn