3.2 Access to C global variables from assembly code

Global variables can only be accessed indirectly, through their address. To access a global variable, use the IMPORT directive to do the import and then load the address into a register.

You can then access the global variable using load and store instructions, depending on its type.

For unsigned variables, for example, use:

  • LDRB/STRB for char

  • LDRH/STRH for short

  • LDR/STR for int.

For signed variables, use the equivalent signed instruction, such as LDRSB and LDRSH.

Small structures of less than eight words can be accessed as a whole using the LDM and STM instructions. Individual members of structures can be accessed by a load or store instruction of the appropriate type. You must know the offset of a member from the start of the structure in order to access it.

The following example loads the address of the integer global variable globvar into R1, loads the value contained in that address into R0, adds 2 to it, then stores the new value back into globvar.

Accessing global variables

    PRESERVE8
    AREA     globals,CODE
    EXPORT    asmsubroutine
    IMPORT    globvar
asmsubroutine
    LDR  R1, =globvar   ; read address of globvar into R1
    LDR  R0, [R1]       ; load value of globvar
    ADD  R0, R0, #2
    STR  R0, [R1]       ; store new value into globvar
    BX   lr
    END
Non-ConfidentialPDF file icon PDF versionARM DUI0471M
Copyright © 2010-2016 ARM Limited or its affiliates. All rights reserved.