In modern build systems, the linker plays a critical role in producing the final executable or library by combining compiled object files and resolving symbols. While this step often runs behind the scenes, differences between linkers - such as GNU ld, LLVM lld, MSVC linker, or mold - can affect build speed, binary size, and supported features. For this reason, detecting the linker within a CMake project can be valuable when fine-tuning build behavior or applying linker-specific options. This tutorial shows how to check which linker is used in CMake.
Once a language like C++ is enabled, CMake defines the variable CMAKE_CXX_COMPILER_LINKER_ID, which indicates the linker associated with the selected compiler. This value can be used in conditional statements to customize build settings. Here is simple CMakeLists.txt how to use this variable:
cmake_minimum_required(VERSION 4.2)
project(myapp)
set(CMAKE_CXX_STANDARD 17)
if (CMAKE_CXX_COMPILER_LINKER_ID STREQUAL "GNU")
message(STATUS "ld")
elseif (CMAKE_CXX_COMPILER_LINKER_ID STREQUAL "MOLD")
message(STATUS "mold")
elseif (CMAKE_CXX_COMPILER_LINKER_ID STREQUAL "MSVC")
message(STATUS "MSVC")
elseif (CMAKE_CXX_COMPILER_LINKER_ID STREQUAL "LLD")
message(STATUS "lld")
endif ()
add_executable(${PROJECT_NAME} main.cpp)
CMake assigns the CMAKE_<LANG>_COMPILER_LINKER_ID variable automatically when a language is enabled. Common values include GNU, MOLD, MSVC, LLD, and others depending on the toolchain. The complete list of supported linker IDs is available in the official CMake documentation.
For C-based projects, replace CXX with C (resulting in CMAKE_C_COMPILER_LINKER_ID). The same naming convention extends to other supported languages.
Leave a Comment
Cancel reply