Kevin Boone

ARM assembly-language programming for the Raspberry Pi

5. Using constants in assembly programming

This example makes a slight imrovement to the readability of the previous one, but no change to its limited functionality.

The example

Here is the code.

// This example illustrate one way to define a constant, to make
//  the code more readble

.text

SYS_EXIT = 1

.global _start

// Exit the program.
//   On entry, r0 should hold the exit code
exit:
    mov    %r7, $SYS_EXIT
    swi    $0

_start:
    mov    %r0, $44
    b      exit

Constants and symbols

The only new feature in this example is the use of a constant symbol that represents the syscall number. You may recall that the syscall sys_exit has syscall number 1. It's perfectly legitmate to use the literal number 1, but using the symbol SYS_EXIT makes the code more readable. If we only use this value once in the program, a simple comment may make its use clear; but if a value is used repeatedly, it's easier to assign a meaningful symbolic name to it. This is particularly the case if the value might change in the future.

we can also define a symbol in either of these two ways, which are synonymous with using the = sign:

    .equ SYS_EXIT 1
    .set SYS_EXIT 1

Symbols defined this way do not have to be literal values -- they can be expressions that can be evaluated at assembly time. For example, it's legitimate, and often useful, to write:

    WIDTH = 2
    HEIGHT = 3
    AREA = WIDTH * HEIGHT
    ...
    mov %r0, $AREA

The r0 register gets assigned the value 6, and we could just as correctly have written:

    AREA = 6 
    ...
    mov %r0, $AREA

Still, it's often much more illustrative to define the constants in such a way as to show how the values are assigned. Since symbol expressions are evaluated at assembly time, it does not affect the operation of the program at run-time in any way to write an expansive set of definitions.

I'll be making more extensive use of symbols as the complexity of the examples increases.

Summary