Stylized QEMU logo with C++ code connected to an ARM64 processor chip

The idea of cross-compilation and emulation

Often in development, we need to write code for hardware that is different from the hardware we are developing on. Now, writing code is not enough to be sure that we are heading in the right direction. We need to compile it and test it.

In some cases, we can transfer our developed code to the hardware where it is supposed to run, install the compiler on that machine, and then compile and run it. For example, if I am writing code and I want it to run on a Raspberry Pi 4, we can transfer the source code to the Pi, install the necessary compiler on the Pi 4, and compile and test it. However, that can be tedious, and it also depends on hardware availability and the test environment. To help with this, we use cross-compilation and emulation.

In cross-compilation, we develop the source code on our favorite host machine, such as a Mac, install a cross-compiler, and then cross-compile it for the target hardware, like, let’s say, a Raspberry Pi 4. In this post, I will explain how this works and how emulation can help us test our cross-compiled code in an ARM64 Linux virtual machine without the physical hardware.

Cross Compilation

We will practice cross-compilation on a host machine running macOS. To cross-compile on the host, the first thing we need to do is install a cross-compiler for the target. We are going to compile a C++ program for ARM64 Linux, and hence we need a compiler that runs on the Mac and produces an ARM64 Linux executable. Let’s do that step by step.

1. Check the host operating system and architecture

Run these commands in macOS Terminal:

sw_vers
uname -m

For example, on an Apple Silicon Mac running macOS 15, the relevant output would look like this. The version numbers will depend on the installed macOS release.

ProductName: macOS
ProductVersion: 15.x
BuildVersion: …
arm64

On an Intel Mac, the last line will be:

x86_64

uname -m identifies the architecture reported to the running process. Use a native terminal session on Apple Silicon because a terminal running under Rosetta can report x86_64.

On an Intel Mac, the host is x86-64 and the executable will target AArch64. On an Apple Silicon Mac, the processor architecture is already ARM64, but the host runs macOS and the executable will target Linux. We still need the Linux cross-compiler.

2. Install the ARM64 Linux cross-compiler

Now, Raspberry Pi 4 has a processor capable of running 64-bit ARM code. So we need a cross-compiler that runs on the Mac but can build for ARM64 Linux. Later, we will use QEMU to run an ARM64 Linux machine. First, install the cross-compiler and executable inspection tools on the host.

The messense/macos-cross-toolchains Homebrew tap provides the GNU toolchain for this exercise. Its formula selects a macOS build for either Apple Silicon or Intel and links the toolchain’s commands into Homebrew’s bin directory.

With Homebrew installed, run these commands in macOS Terminal:

brew tap messense/macos-cross-toolchains
brew install messense/macos-cross-toolchains/aarch64-unknown-linux-gnu

The toolchain includes the target development libraries and tools such as readelf and objdump for inspecting the generated executable. Check the installed commands and the compiler target:

aarch64-unknown-linux-gnu-g++ --version
aarch64-unknown-linux-gnu-g++ -dumpmachine
aarch64-unknown-linux-gnu-readelf --version
aarch64-unknown-linux-gnu-objdump --version

The name aarch64-unknown-linux-gnu-g++ identifies the target architecture (aarch64), vendor field (unknown), operating system (linux), GNU environment (gnu), and C++ compiler driver (g++). The compiler itself runs on macOS. Its generated machine code and linked libraries are for the Linux target.

3. Create the C++ source file

For testing our cross-compilation setup, let’s create a source file on the host. Use your Mac home directory for this example so that the transfer command in step 14 can find the executables.

cd ~

Example 1: arm64_cross_compile_test.cpp

#include <iostream>
int main()
{
#if defined(__aarch64__)
std::cout << "Compiled for AArch64\n";
#else
std::cout << "Compiled for another architecture\n";
#endif
std::cout << "Pointer size: " << sizeof(void*) << " bytes\n";
}

The preprocessor selects the message during compilation. GCC defines __aarch64__ for its AArch64 target, so the first message identifies the compilation target’s processor architecture. sizeof(void*) reports the size of a pointer in the compiled program’s data model. It is eight bytes in this ARM64 Linux build.

4. Cross-compile the program

Build the executable on the Mac:

aarch64-unknown-linux-gnu-g++ \
-std=c++17 -O2 -Wall -Wextra -Wpedantic \
-static-libstdc++ -static-libgcc \
arm64_cross_compile_test.cpp \
-o arm64_cross_compile_test

The toolchain selects the AArch64 Linux target whether it is running on an Intel Mac or an Apple Silicon Mac.

The -static-libstdc++ option links the GNU C++ standard library into the executable. This lets us use the Mac’s cross-toolchain without requiring the Ubuntu 22.04 guest to supply the same version of libstdc++.so.6. The -static-libgcc option does the same for the GCC support library. The executable still links dynamically against the GNU C Library, glibc.

5. Inspect the generated executable

Use the file command on the host to identify the executable:

file arm64_cross_compile_test

Typical output for a build with position-independent executables enabled looks like this:

arm64_cross_compile_test: ELF 64-bit LSB pie executable, ARM aarch64,
version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux-aarch64.so.1, …
  • ELF identifies the executable format. A native macOS executable would show Mach-O here.
  • 64-bit LSB identifies a 64-bit, little-endian executable.
  • ARM aarch64 identifies the target architecture.
  • dynamically linked and interpreter /lib/ld-linux-aarch64.so.1 tell us that the executable requests the ARM64 Linux dynamic loader.
  • pie executable, when present, means it is a position-independent executable.

For more detail, you may inspect the ELF header, program headers, and dynamic section:

aarch64-unknown-linux-gnu-readelf -h arm64_cross_compile_test
aarch64-unknown-linux-gnu-readelf -l arm64_cross_compile_test
aarch64-unknown-linux-gnu-readelf -d arm64_cross_compile_test

Typical header fields for a PIE build are:

Class: ELF64
Data: 2's complement, little endian
Type: DYN (Position-Independent Executable file)
Machine: AArch64
Entry point address: 0x…

The ELF type DYN is also used for shared objects. In a PIE build, the interpreter and PIE information identify this file as a position-independent executable. A toolchain configured to build a non-PIE executable by default can show EXEC instead. The entry point is the startup address in the executable, which is distinct from the C++ main function. Its exact value depends on the build.

In the dynamic section, look for an entry for the C library:

(NEEDED) Shared library: [libc.so.6]

NEEDED lists the shared libraries required directly by the executable. The libraries can require further libraries themselves. For this example, libstdc++.so.6 should be absent because we linked the C++ standard library statically. If the output includes BIND_NOW or NOW, those flags request symbol binding during loading.

Before transferring the executable, check the glibc symbol versions it requires:

aarch64-unknown-linux-gnu-objdump -T arm64_cross_compile_test |
grep '\*UND\*' |
grep 'GLIBC_'

Read the numeric versions in the output. Ubuntu 22.04 for ARM64 supplies glibc 2.35, so required versions such as GLIBC_2.17 and GLIBC_2.34 are within range. A requirement such as GLIBC_2.38 is too new. If you see a version above 2.35, rebuild the dynamic executable with a cross-toolchain targeting glibc 2.35 or earlier before testing it on this guest. The fully static build in step 7 can be tested independently.

Emulation Using QEMU

Our cross-compiled binary is ready to be tested, but we don’t have the target hardware. How do we test it then? For testing the cross-compiled binary, we will use an emulation tool called QEMU. Follow the steps below to set up QEMU and run the binary on it.

6. Run the executable using an ARM64 Linux guest

On a Linux host, QEMU’s user-mode emulator can execute the target program and translate supported Linux system calls for the host kernel. That is what allows the Ubuntu-host version of this exercise to run qemu-aarch64 -L /usr/aarch64-linux-gnu before booting a guest.

On macOS, we will run the executable inside a full ARM64 Linux guest instead. This applies to Apple Silicon as well as Intel. Matching the processor architecture alone does not supply the Linux system calls or the Linux loader that the program needs. We will start the guest in step 12 and run the program in step 15.

7. Compare dynamic and static linking

Build a second executable with -static on the host:

aarch64-unknown-linux-gnu-g++ \
-std=c++17 -O2 -Wall -Wextra -Wpedantic -static \
arm64_cross_compile_test.cpp \
-o arm64_cross_compile_test_static
file arm64_cross_compile_test_static

For this program, static linking includes the required library code in the executable, including the C library. The executable still contains ARM64 instructions and uses Linux services. Compare the file sizes and inspect the static executable’s dynamic section:

ls -lh arm64_cross_compile_test arm64_cross_compile_test_static
aarch64-unknown-linux-gnu-readelf -d arm64_cross_compile_test_static

For a conventional fully static executable, the expected readelf output is:

There is no dynamic section in this file.

The first executable already contains the C++ standard library, so the size difference will not match the original Ubuntu-host example. The useful distinction here is that the first executable requests the Linux dynamic loader and the fully static executable does not.

8. Install the full-system QEMU tools

The next stage creates a separate ARM64 Linux machine. Install the following packages on the Mac.

On an Apple Silicon Mac using Homebrew, run:

brew install qemu xorriso

On an Intel Mac using MacPorts, run:

sudo port install qemu xorriso

An Intel reader following these commands will have both package managers installed: Homebrew for the cross-compiler in step 2 and MacPorts for QEMU and xorriso. Homebrew no longer builds new Intel bottles. If you already have a working Homebrew installation of QEMU and xorriso on Intel, you can use it and follow the Homebrew firmware instructions in step 12.

The QEMU package supplies the ARM system emulator qemu-system-aarch64, the ARM64 UEFI firmware, and the disk tool qemu-img. We will use xorriso to prepare the first-boot configuration disk. Check the installed tools:

qemu-system-aarch64 --version
qemu-img --version
xorriso -version

9. Download the ARM64 Ubuntu image

Create a dedicated directory on the host:

mkdir -p ~/qemu_arm64_lab
cd ~/qemu_arm64_lab

Download the ARM64 Ubuntu Server cloud image:

curl -fLO https://cloud-images.ubuntu.com/releases/jammy/release/ubuntu-22.04-server-cloudimg-arm64.img

This image contains an installed operating system and boots through UEFI. Use the same ARM64 image on both Intel and Apple Silicon Macs.

10. Create the guest’s working disk

Create a QCOW2 working disk backed by the downloaded image, then expand its virtual capacity. Run these commands once during initial setup, with the guest stopped:

qemu-img create -f qcow2 \
-F qcow2 \
-b "$PWD/ubuntu-22.04-server-cloudimg-arm64.img" \
ubuntu_arm64_lab.qcow2
qemu-img resize ubuntu_arm64_lab.qcow2 12G

The working disk records the absolute path to the downloaded image. Keep that image at the recorded location while using this working disk.

11. Prepare the guest account and first-boot configuration

In ~/qemu_arm64_lab on the host, create the cloud-init user configuration. Replace the example password with your own before creating the seed disk.

cat > user-data <<'EOF_USER_DATA'
#cloud-config
hostname: arm64-lab
users:
- name: lab
groups: [sudo]
shell: /bin/bash
sudo: "ALL=(ALL) ALL"
lock_passwd: false
plain_text_passwd: 'Arm64Lab2026'
ssh_pwauth: true
chpasswd:
expire: false
EOF_USER_DATA

This creates the lab account with Bash, gives it access to sudo, and enables password authentication for SSH. expire: false keeps the configured password usable without a forced change at first login.

The user-data file and generated seed disk contain the configured password in plain text. Create the instance metadata:

cat > meta-data <<'EOF_META_DATA'
instance-id: arm64-lab-001
local-hostname: arm64-lab
EOF_META_DATA

Create the configuration disk:

xorriso -as mkisofs -o seed.img -V cidata -J -r \
user-data meta-data

xorriso packages the files into a disk labeled cidata that cloud-init can read through its NoCloud data source. QEMU will attach this disk alongside the operating-system disk.

12. Start the ARM64 guest on the Mac

From ~/qemu_arm64_lab on the host, locate the ARM64 UEFI firmware. Choose the command that matches how you installed QEMU.

For Homebrew QEMU, run:

firmware="$(brew --prefix qemu)/share/qemu/edk2-aarch64-code.fd"

For MacPorts QEMU, run:

firmware="$(port -q contents qemu |
awk '/\/edk2-aarch64-code\.fd$/ {print $1; exit}')"

Check the selected file before starting the guest:

ls -lh "$firmware"

Once ls shows the firmware file, launch the virtual machine in the same terminal. The command below uses software emulation on either Mac.

qemu-system-aarch64 \
-name arm64-lab \
-machine virt \
-accel tcg \
-cpu cortex-a72 \
-smp 2 \
-m 2048 \
-bios "$firmware" \
-drive if=none,file=ubuntu_arm64_lab.qcow2,format=qcow2,id=osdisk \
-device virtio-blk-pci,drive=osdisk \
-drive if=none,file=seed.img,format=raw,id=seed \
-device virtio-blk-pci,drive=seed \
-netdev user,id=net0,hostfwd=tcp:127.0.0.1:2222-:22 \
-device virtio-net-pci,netdev=net0 \
-display none \
-serial stdio \
-monitor none

On an Intel Mac, keep -accel tcg and -cpu cortex-a72 for this ARM64 guest. On an Apple Silicon Mac, you can use hardware acceleration by replacing those two lines with:

    -accel hvf \
    -cpu host \

The command stays running while the guest is active. Open a second host terminal for SSH and file transfers. With the -serial stdio setup shown above, pressing Ctrl+C in the terminal running QEMU can terminate the VM immediately, without giving Ubuntu a chance to shut down. Use sudo poweroff inside the guest when you are finished.

The options configure the following parts of the machine:

OptionPurpose
-machine virtSelects the generic ARM virtual platform.
-accel tcgUses software CPU emulation for the ARM64 guest on an Intel or Apple Silicon Mac.
-cpu cortex-a72Selects the emulated CPU model.
-accel hvf and -cpu hostOn Apple Silicon, use hardware acceleration and the host CPU model in place of the two options above.
-smp 2Presents two virtual CPUs.
-m 2048Allocates 2,048 MiB of guest RAM.
-bios "$firmware"Loads the ARM64 UEFI firmware supplied by the QEMU installation.
-drive …id=osdisk and its -deviceAttach the working disk through a VirtIO block device.
-drive …id=seed and its -deviceAttach the first-boot configuration disk.
-netdev user,…Provides user-mode networking and SSH port forwarding.
-device virtio-net-pci,…Presents a VirtIO network interface to the guest.
-display noneRuns the guest without opening a graphical display.
-serial stdioConnects the guest serial port to the Mac terminal.
-monitor noneDisables the separate QEMU monitor console.

The terminal displays the Ubuntu Server text console. Allow first-boot initialization to finish, then press Enter if needed to display the login prompt.

Log in with username lab and the password configured in user-data. Password input normally appears without characters being echoed.

13. Connect to the guest through SSH

The guest can also be reached from a second Mac terminal. First, check the running QEMU process:

pgrep -fl qemu-system-aarch64

Process IDs change between runs. Connect from the host:

ssh -p 2222 lab@127.0.0.1

The forwarding rule sends connections from the host’s loopback port 2222 to guest port 22. The address 127.0.0.1 in this command refers to the Mac. QEMU forwards the connection into the guest. After login, the prompt should look like this:

lab@arm64-lab:~$

To inspect the guest directly, run these commands at the guest prompt:

uname -m
cat /etc/os-release

The architecture should be aarch64 on either Mac. The Ubuntu release should be 22.04 LTS, code-named jammy. An SSH session is also convenient for pasting commands and copying terminal output. The QEMU serial console remains available for guest-side execution in the first terminal.

14. Transfer the cross-compiled executables

Use a host terminal for the transfer. If the current terminal is connected to the guest through SSH, either open another Mac terminal or run exit to leave that SSH session. Copy the two executables from the Mac’s home directory into the guest:

scp -P 2222 \
~/arm64_cross_compile_test \
~/arm64_cross_compile_test_static \
lab@127.0.0.1:~/

The executables are now stored in the guest’s /home/lab directory.

15. Run the programs inside the guest

Reconnect from the Mac with ssh -p 2222 lab@127.0.0.1, or use the serial console. At the guest prompt, run:

cd /home/lab
chmod +x arm64_cross_compile_test arm64_cross_compile_test_static
./arm64_cross_compile_test

For the build that passed the glibc compatibility check in step 5, the expected output is:

Compiled for AArch64
Pointer size: 8 bytes

Now run the fully static executable:

./arm64_cross_compile_test_static

It should print the same two lines. The difference is how the programs start. The first executable uses the guest’s ARM64 dynamic loader and C library. The second already contains the library code it needs.

16. Shut down and restart the guest

Shut down from either the guest’s SSH session or its QEMU serial console:

sudo poweroff

Enter the guest password if prompted. Let Ubuntu finish shutting down before working on its disk files.

To restart, return to ~/qemu_arm64_lab on the Mac and repeat the QEMU launch command from step 12. If you have opened a new terminal, set firmware again first. The working disk retains the transferred executables and guest account. Disk creation, resizing and initial seed creation are performed during setup.

There you go. Once you see Compiled for AArch64 in the Ubuntu guest, you have cross-compiled a C++ program on your Mac, brought up the target Linux environment in QEMU, transferred the binary, and run it without having the physical target hardware. Happy cross-compiling!


Discover more from Tech For Talk

Subscribe to get the latest posts sent to your email.

Leave a Reply