Variables and Assignment


Global and static variables are declared using .data or .bss entries. Local variables are declared by reserving space on the stack at the beginning of the function. This space is given back at the end of the function.

Interestingly, global variables are accessed differently than local variables in assembly language. Global variables are accessed using direct addressing, while local variables are accessed using base pointer addressing. For example, consider the following C code:

 int my_global_var; int foo() {  int my_local_var;  my_local_var = 1;  my_global_var = 2;  return 0; } 

This would be rendered in assembly language as:

  .section .data  .lcomm my_global_var, 4  .type foo, @function foo:  pushl %ebp            #Save old base pointer  movl  %esp, $ebp      #make stack pointer base pointer  subl  $4, %esp        #Make room for my_local_var  .equ my_local_var, -4 #Can now use my_local_var to                        #find the local variable  movl  $1, my_local_var(%ebp)  movl  $2, my_global_var  movl  %ebp, %esp      #Clean up function and return  popl  %ebp  ret 

What may not be obvious is that accessing the global variable takes fewer machine cycles than accessing the local variable. However, that may not matter because the stack is more likely to be in physical memory (instead of swap) than the global variable is.

Also note that in the C programming language, after the compiler loads a value into a register, that value will likely stay in that register until that register is needed for something else. It may also move registers. For example, if you have a variable foo, it may start on the stack, but the compiler will eventually move it into registers for processing. If there aren't many variables in use, the value may simply stay in the register until it is needed again. Otherwise, when that register is needed for something else, the value, if it's changed, is copied back to its corresponding memory location. In C, you can use the keyword volatile to make sure all modifications and references to the variable are done to the memory location itself, rather than a register copy of it, in case other processes, threads, or hardware may be modifying the value while your function is running.




Programming from the Ground Up
Programming from the Ground Up
ISBN: 0975283847
EAN: 2147483647
Year: 2006
Pages: 137

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net