0

I get this error when running the following code, I can't figure out what is the root cause. Anyone can help me spot it, thanks!

/usr/bin/ld: /tmp/ccLgxyJl.o: in function `MyFunctionRunner::callFunc()':
main.cpp:(.text._ZN16MyFunctionRunner8callFuncEv[_ZN16MyFunctionRunner8callFuncEv]+0xb): undefined reference to `MyFunctionRunner::func_'
#include <iostream>
#include <functional>

using namespace std;

class MyClass1{
    public:
        void printX(){
            std::cout<<"print X from MyClass1"<<std::endl;
        }
    
};

class MyClass2{
    public:
        void printX(){
            std::cout<<"print X from MyClass2"<<std::endl;
        }
};


class MyFunctionRunner{
  public:
      static void callFunc(){
         func_(); //Calls the function that's set
      }
      static void setFunc(std::function<void()> func){
         func_ = func; //Sets a function
      }
 private:
     static std::function<void()> func_;
 };
 

template<class MyClass>
void MyFunc(){
   MyClass myObj{};

   MyFunctionRunner::setFunc(
     [myObj]() mutable{
        myObj.printX();
   }); //Passes in a lambda function as a parameter that captures `myObj` by value. 
 };

 
int main() {     
    MyFunc<MyClass1>();
    MyFunc<MyClass2>();
    MyFunctionRunner::callFunc();
    return 0;
}
user1008636
  • 2,989
  • 11
  • 31
  • 45
  • 1
    You have a declaration `static std::function func_;`. Its a static. you need a definition to actually create the instance. – Avi Berger Sep 13 '22 at 01:48
  • I don't think `myObj` is being captured by reference in the lambda, it is being captured by value. Use the following lambda capture: `[&myObj]` or you can elide the specific object and just us `[&]` to capture by reference. – oraqlle Sep 13 '22 at 01:51
  • 1
    @oraqlle if it was captured by ref, rather than the intended by value, what would happen when it almost immediately goes out of scope? – Avi Berger Sep 13 '22 at 02:04

0 Answers0