21 July 2010

Learning basic assembler.

I've been learning assembler, so I can write a code generator for Obelisk. I'm at page 98 of (the PDF version) of Dr Paul Carter's PC Assembly Language.

So far, I've learned how to call C functions. I need to do this because the Obelisk runtime is written in C!

Anyway, it aint much, but here's a 'hello world', written for NASM, the netwide assembler..

hello.asm:




; Hello world program!

; The data segment contains data that is always in memory (unlike the stack)
segment .data
format db 'Hello world!', 10, 0 ; The format string for printf

; The text segment contains the code the machine will execute
segment .text
   global main ; Main must be global for gcc to find it!
   extern printf ; We must declare that printf is defined in another object file.

main: push dword format ; Push the argument to printf on to the stack.
      call printf ; Call printf
      pop eax ; Remove the argument from the stack



This will need to be linked to libc because it uses printf. I'm using gcc because it's simple.
So, in the shell, assemble and link and run with:




$ nasm -f elf hello.asm && gcc hello.o -o hello && ./hello
> Hello world!



On my computer, the object file hell.o is only 608 bytes long

No comments:

Post a Comment