When compiling C++ programs on Linux systems, it can be desirable to link the standard C++ library (libstdc++) statically. This approach embeds the required runtime directly into the executable, avoiding reliance on shared libraries present on the target machine. As a result, deployment becomes more reliable and issues related to missing or incompatible library versions are minimized. This tutorial explains how to statically link to libstdc++ using CMake.
CMake provides a straightforward way to pass linker options via the target_link_options command. The following CMakeLists.txt example shows how to apply static linking using this command:
cmake_minimum_required(VERSION 3.27)
project(myapp)
set(CMAKE_CXX_STANDARD 17)
add_executable(${PROJECT_NAME} main.cpp)
if (LINUX AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
target_link_options(${PROJECT_NAME} PRIVATE -static-libstdc++ -static-libgcc)
endif()
In this configuration, the linker options -static-libstdc++ and -static-libgcc are applied only when building on Linux with either GCC or Clang. These options instruct the linker to include static versions of the standard C++ library and GCC support library within the final binary. This ensures the executable remains self-contained.
Leave a Comment
Cancel reply