Printing to the screen without a db

From OSDev Wiki
Jump to navigation Jump to search

NASM has the ability to create useful macros that have a calling convention similar to BASIC statements. Macros can be used for many purposes, and here one is used to emulate BASIC's PRINT statement.

Note: this macro is designed to be used in real mode only, since it uses BIOS functions, but it can be easily be adapted for other printing methods.

; Null terminated string in SI.
print_string:
     ; Save registers
     push ax
     push bx
     push bp        ; Some BIOSes may clobber this register too.
     mov ah, 0Eh    ; INT 10h teletype function.
 
 .loop:
     lodsb          ; Get byte from string.
     test al, al    ; Null terminator reached?
     jz .done       ; Yes, end printing.
 
     int 10h        ; No, print the character.
     jmp .loop      ; Loop!
 
 .done:
     ; Restore registers
     pop bp
     pop bx
     pop ax
     ret
 
 
 %macro print 1+
     section .data    ; At the end of the binary.
 %%string:
     db %1,0
     section .text    ; Back to where we were.
 
     mov si,%%string
     call print_string    ; Print it out using the print_string function.
 %endmacro

Now print can be used as a regular function or instruction (Note: using this in a bootloader may not work, it messes with the data section).

 print 'Printing without a db in NASM!',0Dh,0Ah    ; Print out a little message!

A little known feature of NASM is the usage of the ` (back quote) character to contain a string that can use C-style escape codes like \n.

See Also

Articles