TExcelTAD

Cross-Compilation

Cross-compiling means building on one kind of machine a program that runs on another: an ARM firmware image on an x86 laptop, a Windows .exe on a Linux CI server, an Android library on a Mac. It's routine in embedded work, mobile apps, game consoles and release pipelines, and it is where hidden assumptions in a build ("the compiler is gcc", "headers are in /usr/include", "I can run what I just built") fall apart.

Build, host and target

GNU tools (Autotools, GCC's own build) use three machine names. The terms are confusing at first because "host" does not mean "the machine I'm sitting at":

Term Meaning Example: building a Raspberry Pi app on a laptop
build the machine running the build x86_64-linux-gnu (the laptop)
host the machine the built program will run on aarch64-linux-gnu (the Pi)
target only for compilers: the machine the built compiler will generate code for (not relevant for an app)

CMake and Meson simplify this to "the machine we build on" and "the machine we build for". Each machine is named by a target triple: arch-vendor-os-abi, for example x86_64-pc-linux-gnu, aarch64-unknown-linux-gnu, x86_64-pc-windows-msvc, arm-none-eabi (bare-metal ARM, no OS), wasm32-unknown-unknown.

Clang: one compiler, many targets

GCC is built for one target; cross-compiling with GCC means installing a separate compiler such as aarch64-linux-gnu-gcc. Clang contains every back end and picks one with --target:

bash · try it yourself
mkdir -p xc && cd xc
printf 'int add(int a, int b) { return a + b; }\n' > add.c
clang -print-target-triple
for t in aarch64-linux-gnu riscv64-linux-gnu x86_64-pc-windows-msvc wasm32-unknown-unknown; do
  clang --target=$t -O2 -c add.c -o add-$t.o
  printf '%-24s ' $t; file -b add-$t.o | cut -d, -f1-2
done
x86_64-pc-linux-gnu
aarch64-linux-gnu        ELF 64-bit LSB relocatable, ARM aarch64
riscv64-linux-gnu        ELF 64-bit LSB relocatable, UCB RISC-V
x86_64-pc-windows-msvc   Intel amd64 COFF object file, not stripped
wasm32-unknown-unknown   WebAssembly (wasm) binary module version 0x1 (MVP)

Four object files for four platforms from one compiler binary, no extra installation needed. Compiling is the easy part.

What fails without a sysroot

As soon as the code includes a header from the C library, the cross build needs that platform's headers and libraries: a sysroot, a directory that looks like the target's / (with usr/include, usr/lib, lib). This machine has x86-64 headers only, and some of them are architecture-specific:

bash · try it yourself
mkdir -p xc && cd xc
printf '#include <stdio.h>\nint main(void) { puts("hi"); return 0; }\n' > hello.c
clang --target=aarch64-linux-gnu -c hello.c -o hello-arm64.o
In file included from hello.c:1:
/usr/include/stdio.h:28:10: fatal error: 'bits/libc-header-start.h' file not found
   28 | #include <bits/libc-header-start.h>
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.

Clang found the generic /usr/include/stdio.h but not the arm64 directory for bits/… headers (on Debian and Ubuntu they live in /usr/include/aarch64-linux-gnu/). Even if you got past the headers, linking needs the arm64 crt1.o, libc.so and the dynamic loader. You get a sysroot by:

  • installing the distribution's cross packages (gcc-aarch64-linux-gnu and libc6-dev-arm64-cross on Debian/Ubuntu), which put the files in /usr/aarch64-linux-gnu/;
  • copying /usr and /lib from a real target device or its OS image;
  • using a vendor SDK (Android NDK, Yocto/Buildroot SDKs, Apple's Xcode SDKs), or a toolchain bundle such as those from Arm, Bootlin or crosstool-NG;
  • using Zig's zig cc, which ships C library sources for many targets and builds them on demand.

Then clang --target=aarch64-linux-gnu --sysroot=/path/to/sysroot hello.c -o hello works like a native build.

A program that needs no sysroot

Code that uses no C library at all doesn't need a sysroot. This "freestanding" program makes the Linux write and exit system calls directly (arm64 numbers 64 and 93), and is linked with LLVM's lld, which handles every architecture:

bash · try it yourself
mkdir -p xc && cd xc
cat > start.c <<'SRC'
static long sys_write(long fd, const char *buf, long len) {
    register long x8 __asm__("x8") = 64;          /* arm64 Linux: write */
    register long x0 __asm__("x0") = fd;
    register long x1 __asm__("x1") = (long)buf;
    register long x2 __asm__("x2") = len;
    __asm__ volatile("svc 0" : "+r"(x0) : "r"(x8), "r"(x1), "r"(x2) : "memory");
    return x0;
}
static void sys_exit(long code) {
    register long x8 __asm__("x8") = 93;          /* arm64 Linux: exit */
    register long x0 __asm__("x0") = code;
    __asm__ volatile("svc 0" : : "r"(x8), "r"(x0));
    __builtin_unreachable();
}
void _start(void) {
    static const char msg[] = "hello from arm64\n";
    sys_write(1, msg, sizeof msg - 1);
    sys_exit(0);
}
SRC
clang --target=aarch64-linux-gnu -ffreestanding -nostdlib -static -fuse-ld=lld -O2 start.c -o hello-arm64
file -b hello-arm64 | cut -d, -f1-2,4
readelf -h hello-arm64 | grep Machine
./hello-arm64 2> err.txt; echo "exit status: $?"
sed 's/.*\(cannot execute\)/\1/' err.txt
ELF 64-bit LSB executable, ARM aarch64, statically linked
  Machine:                           AArch64
exit status: 126
cannot execute binary file: Exec format error

The build is correct, and this x86-64 machine refuses to run it: Exec format error, exit status 126. That's the other half of cross-compiling: you can't run your tests on the build machine. The usual answers are an emulator (qemu-aarch64 in user mode runs single Linux binaries; with binfmt_misc the kernel calls it automatically, which is how docker buildx builds arm64 images on x86), a device farm, or native CI runners for each architecture. Build systems have hooks for this: CMake's CMAKE_CROSSCOMPILING_EMULATOR, Meson's exe_wrapper.

Mixing architectures fails at link time

Objects for different architectures can't be linked together. The linker reads the Machine field from each ELF header:

bash · try it yourself
mkdir -p xc && cd xc
printf 'int f(void) { return 1; }\n' > f.c
printf 'int f(void);\nint main(void) { return f(); }\n' > main.c
clang --target=aarch64-linux-gnu -c f.c -o f-arm64.o
gcc main.c f-arm64.o -o mixed
/usr/bin/ld: f-arm64.o: Relocations in generic ELF (EM: 183)
/usr/bin/ld: f-arm64.o: error adding symbols: file in wrong format
collect2: error: ld returned 1 exit status

EM: 183 is the ELF machine number for AArch64. This error usually means a build reused a stale object or a prebuilt library from the wrong platform: for instance, a cache key that didn't include the target triple.

Toolchain files

Build systems describe a cross setup in a file you pass once, instead of flags sprinkled through the project. A CMake toolchain file (covered in Modern CMake) looks like this:

cmake
# aarch64-linux.cmake: use with  cmake -S . -B build --toolchain aarch64-linux.cmake
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR aarch64)
set(CMAKE_C_COMPILER clang)
set(CMAKE_C_COMPILER_TARGET aarch64-linux-gnu)
set(CMAKE_SYSROOT /opt/sysroots/aarch64-linux)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)   # tools come from the build machine
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)    # libraries and headers only from the sysroot
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)

Meson uses a cross file with the same information, Conan uses a host profile next to a build profile, and Cargo and Go need only a target name (cargo build --target aarch64-unknown-linux-gnu, GOOS=linux GOARCH=arm64 go build) plus a linker for any C parts.

Test yourself

In GNU terminology, you build a Raspberry Pi program on an x86 laptop. What is the 'host'?

  1. The laptop
  2. The Raspberry Pi (where the program will run)
  3. The CI server
  4. The compiler

clang --target=aarch64-linux-gnu -c hello.c fails with 'bits/libc-header-start.h' file not found. What is missing?

  1. An arm64 back end in Clang
  2. A sysroot with the target's C library headers and libraries
  3. The -O2 flag
  4. A newer Clang

Why did ./hello-arm64 exit with status 126?

  1. The build was broken
  2. The kernel can't execute an arm64 binary on an x86-64 machine (Exec format error); an emulator such as qemu-aarch64 is needed
  3. It needs root
  4. _start returned