CMake use MUSL slim libc
CMake can use MUSL slim libc natively (e.g. Alpine Linux), in a Docker container, or by cross-compiling. Cross-compiling in CMake generally uses a toolchain file to set critical variables that can’t be detected automatically. For example, using the x86_64 MUSL binaries from musl.cc, extract the tar file say to ~/musl and then create file ~/musl/musl-toolchain.cmake like:
set(CMAKE_SYSTEM_NAME Linux)
# target system
set(CMAKE_SYSTEM_PROCESSOR x86_64)
# target architecture
set(CMAKE_FIND_ROOT_PATH ${CMAKE_CURRENT_LIST_DIR}/x86_64-linux-musl-native)
# These cross-compilers come from the toolchain downloaded from musl.cc
set(_bin ${CMAKE_FIND_ROOT_PATH}/bin)
set(CMAKE_C_COMPILER "${_bin}/x86_64-linux-musl-gcc")
set(CMAKE_CXX_COMPILER "${_bin}/x86_64-linux-musl-g++")
set(CMAKE_Fortran_COMPILER "${_bin}/x86_64-linux-musl-gfortran")
set(_lib ${CMAKE_FIND_ROOT_PATH}/lib)
set(CMAKE_SYSTEM_LIBRARY_PATH ${_lib})
set(CMAKE_SYSTEM_INCLUDE_PATH ${CMAKE_FIND_ROOT_PATH}/include)
set(CMAKE_EXE_LINKER_FLAGS_INIT -Wl,-rpath-link=${_lib},-rpath=${_lib})
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
Use this to cross-compile a CMake project with MUSL like:
cmake -Bbuild ---toolchain ~/musl/musl-toolchain.cmake
cmake --build build
ctest --test-.dir build
The LINKER_FLAGS allow executables to be run from the host system.