Calls to C from assembly language

The following example is a C function that is to be called from assembler code.

Example 15. Defining the function in C

int g(int a, int b, int c, int d, int e) 
    return a + b + c + d + e;

To call this C function from assembly, specify the the g function symbol with the IMPORT directive:

Example 16. Assembly language call

    ; int f(int i) { return g(i, 2*i, 3*i, 4*i, 5*i); }
    EXPORT f
    IMPORT g           ; i is in R0
    STR lr, [sp, #-4]! ; preserve lr
    ADD R1, R0, R0     ; compute 2*i (2nd param)
    ADD R2, R1, R0     ; compute 3*i (3rd param)
    ADD R3, R1, R2     ; compute 5*i
    STR R3, [sp, #-4]! ; 5th param on stack
    ADD R3, R1, R1     ; compute 4*i (4th param)
    BL g               ; branch to C function
    ADD sp, sp, #4     ; remove 5th param
    LDR pc, [sp], #4   ; return

Show/hideSee also

Copyright © 2010-2012 ARM. All rights reserved.ARM DUI 0471G