save function to same adress in each runtime

Viewed 47

I have an object that has an array of pointers to functions as config value like this:

class Object{
    public:
    bool (*function[2])() = {};
};

bool fooFunc(){return true;}
bool barFunc(){return false;}

Object obj;
void setupObject(){
    obj.function[0] = &fooFunc;
    obj.function[1] = &barFunc;
}

I am on a µC on would like to store the used functions in EEPROM, so that the object can resume with the same config when the program is restarted. Is there a way to write functions specify the address to which a function is written to?

Alternatively, I could make an array of pointers with all functions that are allowed (couple dozens) and only save the function ID, but I don't know how to do that efficiently and with maintainable code. Would using lambda functions here save me some space? Also, that would mean that my functions are always loaded, wouldn't it?

1 Answers

Is there a way to write functions specify the address to which a function is written to?

No. Not in standard C++.

Choosing the address is something that the linker does. How to configure the linker to store the functions in manually chosen address, I don't know; It'll probably depend on what linker you use.

I could make an array of pointers with all functions that are allowed ... Would using lambda functions here

No. Each lambda has a distinct type, and all elements of an array have the same type. You cannot have an array of lambdas.

Related