Compiling mixed C and assembly source files

The Arm assembler armclang is an integrated assembler that is based on LLVM using GNU syntax and reads assembly language source code and outputs object code. The Arm compiler armclang compiles C and C++ source code to object code. 

The Arm linker armlink combines the contents of one or more object files with any required libraries to produce an executable program.

Arm compiler, assembler, and linker are all part of the Arm Compiler 6 toolchain which is inbuilt with Arm DS.  

The following example shows how to use armclang integrated assembler, armclang and armlink from Arm DS to build a project containing both C and assembly source files. 

  1. Create a new C project and add a new source file my_strcopy.s containing the following assembly code:

    #include "my_strcpy.h"
        .section   StringCopy, "ax"
        .balign    8
        .global    mystrcopy
        .type      mystrcopy, "function"
        ldrb       r2, [r1], #1                 ; Load byte and update address
        strb       r2, [r0], #1                 ; Store byte and update address
        cmp        r2, #0                       ; Check for null terminator
        bne        mystrcopy                    ; Keep going if not
        bx         lr                           ; Return

    The function my_strcopy() is exported so that it is available to be used from C, see the following code screenshot:

  2. Add a new source file to the project with the name test.c containing the following C code:

    #include <stdio.h>
    #include <stdlib.h>
    /* Declare the assembly function */
    extern void mystrcopy(char *d, const char *s);
    int main()
      const char *srcstr = "First string - source ";
      char *dststr = "Second string - dest ";
      puts("Before copying:\n");
      printf("  %s\n  %s\n",srcstr,dststr);
      puts("\nAfter copying:\n");
      printf("  %s\n  %s\n",srcstr,dststr);
      return (0);
  3. Build the project.
    The Arm Compiler toolchain does the following:
    • Assembles my_strcopy.s with armclang my_strcopy.o.
    • Compiles test.c with armclang to produce the object file test.o.
    • Links the object files with armlink to produce an executable image.
    • When you run the executable image, it produces the following output:

      Before copying:
      First string - source
      Second string - dest
      After copying:
      First string - source
      First string - source

Previous Next