I am currently working on a project that uses a lot of lambda functions, and I found that they use a lot of stack but I don't understand why. I am a quite new to c++, I am more used to C.
To try to reduce stack usage and to understand how lambda work, I wrote some very simple code reproducing our use of lambdas. I am compiling the following code with gcc and -Os option.
typedef struct structTest
{
uint32_t var1;
uint32_t var2;
} structTest;
// Test 1
int main()
{
dostuff( [&]() -> structTest{ structTest $; $.var2 = 24; $.var1 = 48; return $; }() );
}
// Test 2
int main()
{
dostuff( [&]() -> structTest{ structTest $; $.var2 = 24; $.var1 = 48; return $; }() );
dostuff( [&]() -> structTest{ structTest $; $.var2 = 13; $.var1 = 42; return $; }() );
}
Test 1 uses 8 bytes of stack, which I didn't really expect but can understand, but Test 2 uses 16 bytes of stack and I don't understand why. I would have expected 8 bytes, as in the stack used for the first call of the function would be reused for the second call.
I would have guessed that the two structure would not be reserved on stack.
Stack was analyzed with Ozone and runs on a Nucleo L476RG. This project is an IoT project, where ROM and stack are precious.
Is there a way to keep this kind of structure/lambda usage but reduce stack usage ?