Skip to content
systemcoding.dev
Assembly

Write Your First Cortex-M Assembly Function and Call It From C

Write a Thumb-2 function in a .S file, declare it in C, build with arm-none-eabi-gcc 14 and see exactly how arguments and the result travel in registers.

7 min read
Summarize in AI
Flat illustration of an assembly listing with addresses and mnemonics, with the Arm, C and GNU logos.

The smallest useful assembly project on a Cortex-M is one function in a .S file that C code calls like any other. Doing it once shows you the whole contract: where the arguments arrive, where the result goes, which directives make the linker treat the symbol as Thumb code, and what the compiler's own call looks like next to yours. This post builds a function that returns the larger of two unsigned integers, using Arm GNU Toolchain 14 (arm-none-eabi-gcc 14, binutils 2.42) for a Cortex-M4. The same source assembles for any core from the Cortex-M0 up with a changed -mcpu.

The C side

C needs a prototype so it knows the argument and return types. The function takes two uint32_t and returns one.

main.cc
#include <stdint.h>

uint32_t max_u32(uint32_t a, uint32_t b);

volatile uint32_t result;

int main(void)
{
    result = max_u32(7u, 42u);
    for (;;) { }
}

Nothing here says the function is written in assembly. The compiler emits a call, bl max_u32, and expects the function to follow the Arm procedure call standard for 32-bit Arm, AAPCS: the first four 32-bit arguments travel in r0 to r3, and a 32-bit result comes back in r0. So a is in r0, b is in r1, and the function has to leave its answer in r0.

The assembly side

max.Sasm
        .syntax unified
        .cpu    cortex-m4
        .thumb

        .text
        .global max_u32
        .type   max_u32, %function
        .thumb_func
max_u32:
        cmp     r0, r1          // compute r0 - r1, set flags, discard result
        bcs     1f              // carry set means r0 >= r1 (unsigned)
        mov     r0, r1          // r0 < r1: the answer is b
1:
        bx      lr              // return, result already in r0
        .size   max_u32, .-max_u32

Go through the directives, because forgetting any of them gives a build that links and then crashes:

  • .syntax unified selects UAL, the syntax every current manual uses. Without it GNU as expects the older divided syntax for Thumb, and movs and bcs are read differently.

  • .cpu cortex-m4 tells the assembler which instructions are legal. The same directive with cortex-m0 would reject encodings that need Thumb-2.

  • .thumb selects Thumb encoding for what follows. A Cortex-M has no other choice, but the assembler still has to be told.

  • .global exports the symbol so the linker can resolve the call from main.o.

  • .type max_u32, %function marks the symbol as a function, which lets the linker and debugger treat it correctly.

  • .thumb_func is the one beginners miss. It makes the assembler set the lowest bit of the symbol's address. The core only runs Thumb, and bl and bx need that bit set to stay in Thumb state, so a symbol that the assembler does not know is Thumb code can end up with an even address, and a call through it faults.

  • .size records the length for tools like nm -S and the debugger.

The body is three instructions. cmp r0, r1 subtracts r1 from r0 just to set the flags. In an unsigned subtraction, the carry flag is set when no borrow was needed, that is when r0 >= r1, so bcs (branch if carry set, also written bhs) skips the move. Otherwise mov r0, r1 replaces the first argument. The label 1: is a numeric local label, and 1f means the next one forward.

Building it

Compile the C file and assemble the .S file with the same driver. Using gcc on a .S file runs the C preprocessor first, which lets you use #include and #define in assembly.

Shell
arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -O1 -c main.c -o main.o
arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -c max.S -o max.o
arm-none-eabi-objdump -d max.o

The disassembly of the assembly object is:

Text
00000000 <max_u32>:
   0:	4288      	cmp	r0, r1
   2:	d200      	bcs.n	6 <max_u32+0x6>
   4:	4608      	mov	r0, r1
   6:	4770      	bx	lr

All four instructions are 16 bits: 0x4288 for cmp, 0xd200 for bcs.n, 0x4608 for mov r0, r1 and 0x4770 for bx lr. The assembler turned the label 1f into the address 6 and picked the short .n branch form on its own. The offset field of 0xd200 is zero because the branch target is the instruction right after the next one, and the pipeline offset of four bytes already accounts for it.

Link with your startup code and linker script as usual. If you do not have those yet, you cannot run this on hardware, but you can still check what the compiler does with the call:

Shell
arm-none-eabi-objdump -d main.o
Text
00000000 <main>:
   0:	b508      	push	{r3, lr}
   2:	212a      	movs	r1, #42	@ 0x2a
   4:	2007      	movs	r0, #7
   6:	f7ff fffe 	bl	0 <max_u32>
   a:	4b02      	ldr	r3, [pc, #8]	@ (14 <main+0x14>)
   c:	6018      	str	r0, [r3, #0]
   e:	e7fe      	b.n	e <main+0xe>

r0 holds 7 and r1 holds 42 before the bl, exactly as the standard says. The bl target shows as 0 because it is a relocation the linker will fill in. After the call, str r0, [r3, #0] stores the result, again from r0. The exact disassembly of your build may differ in register choice and layout, but the argument registers do not.

What this function is allowed to touch

Your function used only r0 and r1, so it had nothing to be careful about. AAPCS lets a callee freely change r0 to r3 and r12. If you need r4 to r11, you must save them on entry and restore them on exit; push {r4, lr} and pop {r4, pc} is the standard pair. A function that calls another function with bl has to save lr too, or the return address is lost.

The stack must also stay 8-byte aligned at every public interface under AAPCS, which matters when you call back into C that uses double or long long. Pushing an odd number of registers breaks that alignment, so pad when you cross the boundary.

Debugging the first call

If the program faults on the first bl, check the symbol address first. On the final linked image, the address of max_u32 should be odd, and nm shows it that way when .thumb_func was used:

Shell
arm-none-eabi-nm firmware.elf | grep max_u32
Text
08000141 T max_u32

An even address in the final image means the directive is missing. In the unlinked object max.o the symbol reads as 00000000, which proves nothing either way, so always check the linked file.

Passing and returning more than registers hold

The example used two 32-bit arguments, and one result. Real functions need more, so it helps to know what happens at the edges. If your assembly function takes five arguments, the fifth is not in a register. It sits on the stack at [sp] when your function begins, because the caller stored it before the bl. A function that does push {r4, lr} first has moved sp down by 8 bytes, so the fifth argument is now at [sp, #8]. Forgetting that offset is the single most common reason a hand-written function sees garbage in its fifth argument.

A 64-bit result comes back in r0 and r1, low word first. A function that returns a pointer or a bool uses r0 like any other 32-bit value. A function that returns nothing may leave r0 as it pleases, which is why you cannot use a call's r0 as a success flag in a void function.

Testing without hardware you do not have

You do not need a board to confirm the calling convention. Read the disassembly of the compiler's own call, as shown above, and compare with your function's expectations. Then write a C stub that calls your function with a recognizable pair of arguments, such as 0x1111 and 0x2222, and check in the listing that those values are loaded into r0 and r1 before the bl. The register assignment is fixed by the standard, so a listing is enough to prove your side of the interface.

Mistakes worth avoiding on day one

Leave the .s extension for files that need no preprocessing, and use .S when you want #include or #define. The two behave differently in arm-none-eabi-gcc, and a .s file that contains a #define fails with a confusing syntax error. Keep one function per .text.name section if you later want --gc-sections to drop unused code. And always end the function with .size, so nm -S and debuggers report its true length.

Also inEmbedded
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.