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

consider these files:

ph:

#ifndef _p_h_ #define _p_h_ class p{ public: static void set_func(int(*)()); private: static int (*sf)(); }; #endif 

p.cpp:

 #include "ph" #include <cstdio> int (p::*sf)() = NULL; //defining the function pointer void p::set_func(int(*f)()){ sf = f; } 

main.cpp:

 #include "ph" #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 the following:

 $ 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 

a

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

compiles correctly.

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

Thanks.

+6
source share
4 answers

Your attempt to define p::sf is incorrect - yours is a definition of a global variable called sf , which is of type int (p::*)() , that is, 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; 
+12
source

The difference is that the error only occurs when the program is actually linked. The problem is declaring a static function pointer. The correct syntax is:

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

You define a pointer to a member function, not a pointer to a function. I'm not sure what the correct syntax is, but I would try something like this:

 int (*p::sf)() = NULL; 
+3
source

I will not give another answer (the correct answer is ildjarn), but I offer you another way to achieve the goal without static initialization (and the burden that this implies)

 class p{ public: typedef int (*func_t)(); static void set_func(func_t v) { func_t& f = getFuncRef(); f = v; } static void call_func() { func_t& f = getFuncRef(); assert( f != 0); f(); } private: static func_t& getFuncRef() { static func_t sf = 0; return sf; } }; 

this way you delegate static initialization to a static function variable that has no problems with the initialization order, which affects the static data variables, and is lazy initialized

+1
source

Source: https://habr.com/ru/post/899719/


All Articles