Cross-compiling for arm64 using visual studio and WSL2 is generating x64 binary

Summary

Cross-compiling for ARM64 using Visual Studio 2022 and WSL2 resulted in x64 binaries instead of the expected ARM64 output. Despite correct configurations and toolchains, the build system defaulted to the host architecture, ignoring the target platform.

Root Cause

The root cause was Visual Studio’s default behavior of using the host toolchain (x64) instead of the WSL2-based ARM64 toolchain. The WSL2 GCC Toolset was not properly invoked for cross-compilation, leading to the incorrect architecture.

Why This Happens in Real Systems

  • Toolchain Mismatch: Visual Studio defaults to the host toolchain unless explicitly overridden.
  • Configuration Inconsistency: The .vcxproj file lacked explicit toolchain specification for ARM64 builds.
  • WSL2 Integration: WSL2 toolchains require explicit configuration in Visual Studio to avoid host architecture fallback.

Real-World Impact

  • Binary Incompatibility: ARM64 systems cannot execute x64 binaries, causing runtime failures.
  • Development Delays: Debugging cross-compilation issues consumes significant time.
  • Resource Waste: Incorrect builds lead to wasted CI/CD resources and deployment failures.

Example or Code (if necessary and relevant)



  WSL2_GCC_ARM64
  /root/arm64-toolchain/bin/g++%(AdditionalOptions)

How Senior Engineers Fix It

  1. Explicit Toolchain Configuration: Specify the ARM64 toolchain in the .vcxproj file.
  2. Environment Variables: Set CC and CXX to point to the ARM64 compiler in WSL2.
  3. Custom Build Steps: Override default build commands to use the WSL2 ARM64 toolchain.
  4. Validation: Use file command in WSL2 to verify the binary architecture post-build.

Why Juniors Miss It

  • Assumption of Defaults: Juniors often assume Visual Studio will automatically handle cross-compilation.
  • Lack of Toolchain Awareness: Limited understanding of how toolchains are selected in MSBuild projects.
  • Overlooking WSL2 Integration: Failure to recognize WSL2 as a separate environment requiring explicit configuration.

Leave a Comment