There are instances where you may want to run (some) code in SRAM instead of from flash. For example, if you are writing an IAP (In-system Application Programming) bootloader where the flash content will be replaced, then the code must not reside in the flash page that is being erased.
Placing the code in SRAM is a good method of doing that, and fortunately GCC provides an easy way to define such a function. The code in question must be part of the flash image to begin with (among other things, SRAM content is not retained between power cycle), and then copied to SRAM before execution. All the references to the code and from the code to other functions must still be correct, even after the code is running out of SRAM.
In GCC, the following decoration to a function prototype perform all those gymnastic:
__attribute__((long_call, section(".data.ramfunc"))) void func(void)
The “long call” attribute tells the compiler to generate call instructions that can reach far away. This is needed because SRAM memory region is usually quite far away from the flash region.
The section(“.data.ramfunc”) tells the compiler that the function code needs to be relocated to SRAM at program startup. <more stuff later>
If you are writing code or similar code where
you will be erasing the flash, then you must be careful that your
function does not call functions that are in the flash as they may
no longer exist. Keep in mind that C/C++ may generate function call
code to perform more complex operations such as floating-point
arithmetic, or C++ constructors.