I’ve just started making libraries in Arduino. I’ve made a library named inSerialCmd. I want to call a function named delegate() that is defined in the main program file, stackedcontrol.ino, after the inSerialCmd library is included.
When I try to compile, one error is thrown:
…\Arduino\libraries\inSerialCmd\inSerialCmd.cpp: In member function
‘void inSerialCmd::serialListen()’:
…\Arduino\libraries\inSerialCmd\inSerialCmd.cpp:32: error:
‘delegate’ has not been declared
After doing a bit of searching, it seemed that adding the scope resolution operator might do the trick. So I added the “::” before delegate(), now “::delegate()”, but the same error is thrown.
Now I’m stumped.
You cannot and should not directly call a function in a program from a library. Keep in mind a key aspect that makes a library into a library:
So there is a one way dependency, a program depends on a library. This at first glance may seem to prevent you from achieving what you want. You can achieve the functionality you are asking about through what is sometimes referred to as a callback. The main program would provide to the library at runtime a pointer to the function to execute.
You see this in the arduino if you look at how interrupt handlers are installed. This same concept exists in many environments – event listeners, action adapters – all with the same goal of allowing a program to define the specific action that a library cannot know.
The library would store and call the function via the function pointer. Here is a rough sketch of what this looks like: