How to force cmake to link against static version of library...steemCreated with Sketch.

in #cmake9 months ago (edited)

Sometimes it is necessary to force cmake project to link against static version of system library if available, it can be done using following code snippets, which are from cmake package for Ubuntu. Replace Boost with your own package name and boost with package name written in all minuscule (lower-case) letters.

In FindBoost.cmake:

Add before find_library():

if(Boost_USE_STATIC_LIBS)
  set(_boost_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES})
  if(WIN32)
    list(INSERT CMAKE_FIND_LIBRARY_SUFFIXES 0 .lib .a)
  else()
    set(CMAKE_FIND_LIBRARY_SUFFIXES .a)
  endif()
endif()

First it will store original contents of variable CMAKE_FIND_LIBRARY_SUFFIXES to temporary variable, then it will prepend known suffixes of static libraries to the variable. Original contents of the variable will be restored in the following code block.

Add after find_library():

if(Boost_USE_STATIC_LIBS)
  set(CMAKE_FIND_LIBRARY_SUFFIXES ${_boost_ORIG_CMAKE_LIBRARY_SUFFIXES})
endif()

In CMakeLists.txt:

if(STATIC)
  set(Boost_USE_STATIC_LIBS ON)
endif()
find_package(Boost REQUIRED COMPONENTS system filesystem thread date_time chrono regex serialization program_options)

REQUIRED means the library must be found for project configuration to succeed.
COMPONENTS means following package components must be available.