Example of calling printf from assembly on FreeBSD

This is an example assembly language program showing how to call printf in FreeBSD.

        .global main

        .text
main:
        mov     $4, %edi
loop:
        push    %edi
        push    $message          # Address of string to output
        call    printf
        dec     %edi
        jnz     loop
        
        push    $0
        call    exit
        
message:
        .ascii  "Hello, world %d\n\0"

(download)

The output of the example looks like this:

Hello, world 4
Hello, world 3
Hello, world 2
Hello, world 1

To build the program, it's necessary to link with /usr/lib/crt1.o, /usr/lib/crti.o, and /usr/lib/crtn.o. The following makefile illustrates the steps:

all: cp.txt

cp:     cp.o
        ld -o cp cp.o /usr/lib/crt1.o /usr/lib/crti.o /usr/lib/crtn.o -lc

cp.o:   cp.s
        cc -c cp.s

cp.txt: cp
        ./cp > $@

clean:
        -rm -f cp cp.txt

(download)

Web links


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer