A. Let's experience the feeling of programming under Linux, see the code
[section. data]; Data in this Strhellodb "Hello, world!", 0ahstrlenequ$-strhello[section. Text]; Code in this global _start; We must export _start this portal so that the linker can recognize _start:movedx, STRLENMOVECX, STRHELLOMOVEBX, 1moveax, 4; sys_writeint0x80; System call MOVEBX, 0moveax, 1; sys_exitint0x80; System calls
Compile method:
Nasm-f elf Hello.asm-o hello.o
Ld-m elf_i386-s-o Hello hello.o
./hello
Run the result is print out Hello, world!
The entry point defaults to _start, and we will not only define it, but also export it through the global keyword so that the linker can find it. Two system calls do not need to be delved into, because in our own OS there is no system call to Linux at all.
B. Assembly and C synchronous use
; Compile the link method; (The '-s ' option for LD means "strip All");; $ nasm-f elf Foo.asm-o foo.o; $ gcc-c Bar.c-o bar.o; $ ld-s hello.o bar.o-o foobar; $./foobar; the 2nd one; $extern Choose; int choose (int a, int b); [section. data]; Data in this num1stdd3num2nddd4[section. Text]; Code in this global _start; We must export the _start to allow the linker to identify the global myprint; Export this function in order for BAR.C to use _start:pushdword [num2nd]; '. Pushdword [num1st]; | Callchoose; | Choose (num1st, num2nd); Addesp, 8; /MOVEBX, 0moveax, 1; sys_exitint0x80; system calls; void Myprint (char* msg, int len) Myprint:movedx, [ESP + 8]; LENMOVECX, [ESP + 4]; MSGMOVEBX, 1moveax, 4; sys_writeint0x80; System call RET
1. Because the function myprint () is used in bar.c, it is exported using the keyword Global.
2. Because the function choose () defined outside this file is used, it is declared with the keyword extern.
3. Either Myprint () or choose (), followed by the C calling convention, followed by a stack of arguments, and the caller cleans up the stack.
void Myprint (char* msg, int len), int choose (int a, int b) {if (a >= b) {Myprint ("the 1st one\n", 13);} Else{myprint ("The 2nd one\n", 13);} return 0;}
The process of compiling and executing:
Nasm-f Elf-o foo.o foo.asm
Gcc-m32-c-O bar.o bar.c
Ld-m elf_i386-s-o foobar foo.o bar.o
./foobar
Operation Result: the 2nd one
With the keyword global and extern it's easy to get around the assembly and the C code freely.
" Source "
Linux Kernel Series-10. Kernel HelloWorld of operating system development