Search code examples
c++referencenodemcuplatformio

Give Reference to an Object in an other file results in "..." is not captured (Node MCU)


I having problems with giving over references in c++ for a node mcu. Im compiling with Platform IO (I tried Arduino also but had similar problems) i structed my class like that in a .h

class mess_server{
  private:
  public:
  int brerechnung_proz(Kalibrierung& kalibrierung, kali_dat& dat);
  void server_init(Kalibrierung& kalibrierung, kali_dat& dat);
};

in a .cpp i declare the funktion

void mess_server::server_init( Kalibrierung& kalibrierung, kali_dat& dat){
 ...
}

and from the main.cpp i call the Funktion like that:

...
Mess_server.server_init();
...

when I try to compile that, the compiler give me something like that:

src/mess_server.cpp: In lambda function:
  src/mess_server.cpp:63:32: error: 'kalibrierung' is not captured
       dat = kalibrierung.laden();

I got these error for every call of "kalibrierung" and/or "dat"

what am I doing wrong? Im out of ideas.

you can find the complete code here: https://github.com/RubiRubsn/Bewaesserungs_Anlage/tree/main/Bewasserungs%20Anlage%20v2/src


Solution

  • Sorry, I missed the error a bit myself.

    The problem is that you are using a lambda function here and your variable is not known in the lambda function unless you reference it.

    server.on("/Kali_nass", HTTP_GET, [](AsyncWebServerRequest *request){
          dat = kalibrierung.laden(); // not captured inside the lambda
          ...
        });
    

    See Capture variable inside lambda

    So you could do something like this

    server.on("/Kali_nass", HTTP_GET, [&kalibrierung](AsyncWebServerRequest *request){
          dat = kalibrierung.laden(); // captured inside the lambda
        });
    

    Or you can capture all variables inside the lambda. But I am not sure if its ok to override your dat variable her.

    server.on("/Kali_nass", HTTP_GET, [&](AsyncWebServerRequest *request){
          dat = kalibrierung.laden(); // captured inside the lambda
        });
    

    For more information on lambda you can have a look at the documentation

    P.S.

    For future questions on Stackoverflow, any code needed to reproduce the error should be directly visible in the question and not via GitHub ;)

    How to create a Minimal, Reproducible Example