Mysterious "undefined reference to" error in c++

Viewed 46

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;
}
0 Answers
Related