What's the difference between local and global variables in 32-bit X86?

5.5k Views Asked by At

I'm a beginner in the X86 assembly language. Can someone give an example of local and global variables? In particular, how are they initialized? Where are they stored? How are they accessed?

1

There are 1 best solutions below

2
On BEST ANSWER

In x86 assembly, global variables are also referred as static data regions. You can find a good tutorial here - from which I pasted some information. Here is an example of declaring globals:

.DATA           
var DB 64 ; Declare a byte, referred to as location var, containing the value 64.
var2 DB ? ; Declare an uninitialized byte, referred to as location var2.
DB 10 ; Declare a byte with no label, containing the value 10. Its location is var2 + 1.

The globals can then be accessed from any place in the code, in any method without having them passed as arguments.

Local variables are being stored in the stack space, and are processed generally by copying them into registers, doing computations and put them back on the stack.

Let's say you want to call a function. The parameters you pass to the function will be locals for that function.

push [var] ; Push last parameter first
push 216   ; Push the second parameter
push eax   ; Push first parameter last
call _myFunc ; Call the function (assume C naming)
add esp, 12 ; Just discard the locals

When the code enters the function, it needs to get them from the stack, using pop:

pop eax ; get the value you passed as eax content
pop ebx ; get 216 in ebx
pop ecx ; get [var] in ecx

So in eax, ebx, ecx you have values for local variables. After you modify them you can always put them again on the stack and pop them out as you need them.

Hope this helps.