Friday, April 17, 2009

 

Another Hello World program in assembly using puts

Program that displays 'hello world' using 'puts'.



extern puts ; make puts extern

section .data
msg db "Hello World",0

section .text
global main
BITS 32
main:
mov edi, msg
call puts
mov eax, 0
ret


There are minor changes from a standalone assembly program:
1) notice the extern declaration at the top. This declaration is so that the assembler does not complain about the 'call puts' instruction. The extern declaration just says that the function is declared elsewhere externally and the symbol 'puts' will be resolved during link time.


2) notice that '_start' symbol used in stand-alone assembly has been replaced by 'main'. This is necessary because this is not a stand-alone program and will be linked differently. Hence the _start symbol will be used by the linker elsewhere. If you use the _start symbol in your assembly program , then you will get an error during link time about multiple instances of _start.


3) mov edi, msg - moves the address of the msg buffer into edi.

4) call puts - call the putstring function which displays the message on the screen.



To assemble:
nasm -felf print.asm

To link:
gcc print.o -> this will resolve the symbol puts. So when the assembly code calls puts it will know which function to transfer control to.

Run:
a.out

------------------------------------------------------------------------------------------------------------------------------------
It is also useful to write a simple C program (for eg: hello world program), then use gcc with the -S switch to generate a .S file that contains the assembly. Keep in mind that the assembly generated thus uses the GNU assembly syntax.

if your c program is hello.c, you would do this to generate assembly
gcc hello.c -S

This will generate hello.s with the assembly code.

-----------------------------------------------------------------------------------------------

Comments:

Post a Comment

Subscribe to Post Comments [Atom]





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]