How C language and assembly language call each other and Examples
The following two are respectively A foo. asm (assembly language file), bar. c (c language file)
First, let's understand why C language can call assembly language and why it can call C language. In fact, whether it is C or assembly language, the execution is the finalCompile LinkBecome a binary file.
Note:Compile LinkIn this two steps,CompileThe generated binary file is not executable,LinkThen it is an executable binary file.
The compilation and link steps must be clarified here, And the generated file format is also different.
The compiled files are in a certain format, including the function symbol table, parameter table... and other information. This information is mainly provided for the link stage,How is a function called? Is it the symbol of the function used? Therefore, the link stage is to convert the symbol of the function call into a relative address (pay special attention to this stage, because this process makes it possible for C and assembly languages to call each other).
Gcc-m32-c-o bar. o bar. c generates bar. o (intermediate file, not executable file, signed Table, parameter table, etc)
Nasm-f elf-o foo. o foo. asm generates foo. o (intermediate file, not executable file, signed Table, parameter table, etc)
Since all. o intermediate files in the same format are generated, the ld linker can link the two intermediate files to binary executable files,Ld is mainly used to reference the function symbols in bar. o foo. o.To the binary file foobar.Relative address(The relative address is converted to an absolute address when the binary file is loaded into the memory for operation)
Ld-m elf_i386-s-o foobar foo. o bar. o (the link becomes a binary executable file)
Process:
foo.asm
extern choose;[section .data]num1st dq 3num2nd dq 4[section .text]global mainglobal myprintmain: push qword [num2nd] push qword [num1st] call choose add esp,8 mov ebx,0 mov eax,1 int 0x80 ; pop qword [num1st] ; pop qword [num2nd]myprint: mov edx,[esp+8] mov ecx,[esp+4] mov ebx,1 mov eax,4 int 0x80 ; pop qword [num1st] ; pop qword [num2nd] ret
bar.c
void myprint(char * msg ,int len); int choose(int a,int b) { if (a>=b){ myprint(the 1st one ,13);} else { myprint(the 2nd one ,13);} return 0; }