This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Global Vs Local Variable

I have all global variables in my project. Since RAM data size has almost become full, i wanted to replace some of the global variables with local variables in functions. But each local variable declaration seems to take up RAM space as if it is a global variable;

Assume I have few global variables and the data size is 10 bytes

now i add a new function

void function1()
{
char var1,var2,var3,var4,var4,var5,var6,var7,var8,var9,var10;
}

this increases the data size to 20.

adding another function

void function2()
{
char var1,var2,var3,var4,var4,var5,var6,var7,var8,var9,var10;
}

this again increases the data size to 30. What is the point of using local variables in this scenario? It works as if the the variables are declared globally. Shouldn't the data size be global variables 10 bytes + maximum local variable size i.e 10 bytes?

Parents
  • Since the 8051 has lousy instructions for stack-relative memory accesses the compiler converts local data into global data. But it evaluates the call tree to find out which functions will be called in a chain and which functions will never be called at the same time.

    This allows the compiler to overlay multiple "local" variables in the same global address space. So you can save space by having local variables.

    In some situations, you can add more "local" variables without increasing the data space. In some situations, the compiler will have to allocate more global data space because of the call tree analysis.

Reply
  • Since the 8051 has lousy instructions for stack-relative memory accesses the compiler converts local data into global data. But it evaluates the call tree to find out which functions will be called in a chain and which functions will never be called at the same time.

    This allows the compiler to overlay multiple "local" variables in the same global address space. So you can save space by having local variables.

    In some situations, you can add more "local" variables without increasing the data space. In some situations, the compiler will have to allocate more global data space because of the call tree analysis.

Children
  • I have all global variables in my project. Since RAM data size has almost become full, i wanted to replace some of the global variables with local variables in functions. But each local variable declaration seems to take up RAM space as if it is a global variable;

    Per explains very well above, one thing to add: if you use function pointers you will see exactly each local variable declaration seems to take up RAM space as if it is a global variable;

    another thing, the 'overlaying' Per describes above requires optimizer level 2 (or above)