Use mold Linker with CMake

Use mold Linker with CMake

The mold is a linker for Unix systems, designed as a fast, drop-in replacement for tools like GNU ld and LLVM lld. By optimizing parallelism and memory usage, it delivers substantial speed improvements during the linking phase of software builds - while preserving full binary compatibility. This tutorial demonstrates how to use mold linker with CMake.

The following CMakeLists.txt file demonstrates how to integrate mold into the CMake build setup. It checks for the mold binary with find_program, and if available, instructs CMake to use it as the preferred linker by setting the MOLD value for CMAKE_LINKER_TYPE variable.

cmake_minimum_required(VERSION 3.27)
project(myapp)

set(CMAKE_CXX_STANDARD 17)

find_program(MOLD_PROGRAM mold)
if (MOLD_PROGRAM)
    set(CMAKE_LINKER_TYPE MOLD)
    message(STATUS "mold found: ${MOLD_PROGRAM}")
else ()
    message(STATUS "mold not found")
endif ()

add_executable(${PROJECT_NAME} main.cpp)

Here's a simple main.cpp to test the build:

#include <iostream>

int main() {
    std::cout << "Hello world" << std::endl;

    return 0;
}

Execute the following command to create the build files

cmake -S . -B build

Next, run the following command to build the project:

cmake --build build

Examine the compiled executable to ensure mold was used as the linker:

readelf -p .comment build/myapp

Expected output should contain an entry similar to:

String dump of section '.comment':
  [     0]  GCC: (Ubuntu 13.2.0-23ubuntu4) 13.2.0
  [    27]  mold 2.40.4 (083901f42dea2491be8bc7cf6e3b1e2b9a3c850d; compatible with GNU ld)

Leave a Comment

Cancel reply

Your email address will not be published.