The operating mechanism behind the C Language
Objective: To have a preliminary understanding of the experiment code of the assembly language and X86 architecture by analyzing the execution process of converting C language into assembly code
1 #include <stdio.h> 2 3 int g(int x) 4 { 5 return x + 3; 6 } 7 8 int f(int x) 9 {10 return g(x);11 }12 13 int main(void)14 {15 return f(8) + 1;16 }
Lab process Compilation
1. Use cd Desktop to switch to Desktop
2. Use touch 1-1.c to create the 1-1.c file on the desktop.
3. Input our code in the file 1-1.c to save
4. Use this command to compile gcc-S-o main. s main. c-m32 into assembly code.
Result
Row-by-row Analysis
Main:
Pushl % ebp stack top up, open up a new memory, put the memory address at the bottom of the stack to the top of the stack (when the operation is complete, the function can jump back)
Movl % esp, % ebp assigns the esp register value to ebp so that the bottom of the stack is moved up by one
Subl $0x4, % esp moves the top of the stack to one place
Movl 8, (% esp) Put parameter 8 into memory directed by esp
Call f jump to function f
F:
Pushl % ebp stack top up, open up a new memory, put the memory address at the bottom of the stack to the top of the stack (when the operation is complete, the function can jump back)
Movl % esp, % ebp assigns the esp register value to ebp so that the bottom of the stack is moved up by one
Subl $0x4, % esp moves the top of the stack to one place
Movl 8 (% ebp), (% eax) Assign the number 8 to the eax register (eax is used for function return values)
Movl % eax, (% esp) Write eax values into memory
Call g jump to function g
G:
Pushl % ebp stack top up, open up a new memory, put the memory address at the bottom of the stack to the top of the stack (when the operation is complete, the function can jump back)
Movl % esp, % ebp assigns the esp register value to ebp so that the bottom of the stack is moved up by one
Movl 8 (% ebp), % eax assigns 8 to eax
Addl $3, eax executes 8 + 3
Popl % ebp rollback
Ret return function f
F:
Leave deletes the space created for function parameters.
Ret returns the main function.
Main:
Addl $1, % eax + 1
Leave deletes the space created for function parameters.
Ret return
Experiment insights
In a computer, you can execute the operation functions of the memory stack, redirect and pass parameters. In addition, we can understand the program running mechanism through learning and compilation, and help us write streamlined code to improve efficiency.