Prefer Finding Static Libraries Over Shared Libraries using CMake

Prefer Finding Static Libraries Over Shared Libraries using CMake

When developing C or C++ projects with CMake, you may rely on external libraries. By default, CMake looks for shared libraries before static ones. However, some projects require explicitly linking static libraries, even when shared versions are available. Fortunately, CMake provides a way to adjust the search order so that static libraries are preferred first, helping you maintain consistent builds or create fully static binaries. This tutorial explains how to prefer finding static libraries over shared libraries using CMake.

Here's an example CMakeLists.txt file showing how to set this up:

cmake_minimum_required(VERSION 3.27)
project(myapp)

set(CMAKE_CXX_STANDARD 17)

if (MSVC)
    list(INSERT CMAKE_FIND_LIBRARY_SUFFIXES 0 .lib)
else ()
    list(INSERT CMAKE_FIND_LIBRARY_SUFFIXES 0 .a)
endif ()

find_package(ZLIB)

add_executable(${PROJECT_NAME} main.cpp)

By adding the CMAKE_FIND_LIBRARY_SUFFIXES variable modification, CMake will look for .lib files on Windows or .a files on Linux or other systems before searching shared libraries.

After generating build files with:

cmake -S . -B build

You can check which library was picked. CMake will choose static library if available instead of shared library:

-- Found ZLIB: /usr/lib/x86_64-linux-gnu/libz.a (found version "1.2.11")

Leave a Comment

Cancel reply

Your email address will not be published.