Crosscompile using CMake


Published:
Last Modified:
Tags:clang llvm cmake

After debunking crosscompiling beeing hard in an earlier post, i want demonstrate how it can be used to build CMake projects for foreign architectures.

To get started we need the same basic setup as in the previous crosscompilation post. Let’s assume the target environment has been installed into ${HOME}/crosscompile/bookworm-arm64. The project we are going to compile is the CMake version of Lua from github: walterschell/Lua.

The magic sauce to make CMake compile to foreign architectures effortlessly are toolchain files. To compile for x86 on amd64 it is a simple as this:

set(CMAKE_SYSTEM_NAME Linux)

set(CMAKE_C_FLAGS "-m32")
set(CMAKE_CXX_FLAGS "-m32")

But crosscompileing to aarch64 is not much harder:

set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm64)

set(triple arm64-linux-gnu)

set(CMAKE_SYSROOT "$ENV{HOME}/crosscompile/bookworm-arm64")
set(CMAKE_C_COMPILER clang)
set(CMAKE_C_COMPILER_TARGET ${triple})
set(CMAKE_CXX_COMPILER clang++)
set(CMAKE_CXX_COMPILER_TARGET ${triple})

set(CMAKE_LINKER_TYPE "LLD")

set(CMAKE_FIND_ROOT_PATH $ENV{HOME}/crosscompile/bookworm-arm64)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)

I have these files sit around like that:

projects
└── cmake_toolchains
    ├── i386-linux-pc-gnu.cmake
    └── aarch64-linux-pc-gnu.cmake

To configure CMake to use either of these toolchains can be done with the CMAKE_TOOLCHAIN_FILE variable. On the command line it may look like this:

git clone https://github.com/walterschell/Lua.git
mkdir build
cd build
cmake -DCMAKE_TOOLCHAIN_FILE=${HOME}/projects/cmake_toolchains/aarch64-linux-pc-gnu.cmake ../Lua
make