First write a C language code file mstore.c as follows:
#include <stdio.h>
long mult2(long, long);
void multstore(long x, long y, long *dest) {
long t = mult2(x, y);
*dest = t;
}
Use the "-S" option on the command line to see the assembly code generated by the C language compiler:
PS E:\VS Code\VS Code C\chapter 3> gcc -S mstore.c
This will cause GCC to run the compiler and generate an assembly file mstore.s, but does not do any further work. (Under normal circumstances, it will continue to call the assembler to generate object code files).
.file "mstore.c"
.text
.globl multstore
.def multstore; .scl 2; .type 32; .endef
.seh_proc multstore
multstore:
pushq %rbx
.seh_pushreg %rbx
subq $32, %rsp
.seh_stackalloc 32
.seh_endprologue
movq %r8, %rbx
call mult2
movl %eax, (%rbx)
addq $32, %rsp
popq %rbx
ret
.seh_endproc
.ident "GCC: (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0"
.def mult2; .scl 2; .type 32; .endef
If you continue to use the "-C" command-line option, GCC will compile and assemble the code:
PS E:\VS Code\VS Code C\chapter 3> gcc -c mstore.c
This will generate the object code file mstore.o, which is in binary format, so it cannot be viewed directly.
To view the contents of a machine code file, there is a program called a disassembler that is very useful. These programs generate a format similar to assembly based on machine code. The program OBJDUMP (object dump) with the "-d" command line flag can play this role:
PS E:\VS Code\VS Code C\chapter 3> objdump -d mstore.o
The result is as follows: To
generate the actual executable code, the linker must be run on a group of object code files, and this group of object code files must contain a main function. Suppose there is the following function in the file main.c:
#include <stdio.h>
void multstore(long, long, long *);
int main() {
long d;
multstore(2, 3, &d);
printf("2 * 3 --> %ld\n", d);
return 0;
}
long mult2(long a, long b) {
long s = a * b;
return s;
}
Then, use the following method to generate the executable file prog:
PS E:\VS Code\VS Code C\chapter 3> gcc -o prog main.c mstore.c
For example, the
file prog not only contains the code of the two processes, but also contains the code used to start and terminate the program, as well as the code used to interact with the operating system. We can also disassemble the prog file:
PS E:\VS Code\VS Code C\chapter 3> objdump -d prog.exe
At this point, you can run the generated prog file: it is
found that the program running results of the two C files meet expectations.
In the generated mstore.s file:
all .
lines beginning with ' ' are directives to instruct the assembler and linker to work, we can usually ignore these lines. If we remove these, the assembly code with explanation is as follows:
Note the following is the mstore.s file in the Linux environment
multstore:
pushq %rbx
subq $32, %rsp
movq %r8, %rbx
call mult2
movl %eax, (%rbx)
addq $32, %rsp
popq %rbx
ret