How can I link to a static or dynamic boost library using CMake?

I have a CMake project that I sometimes want to compile against static boost libraries, but I also want to simplify just using dynamic libraries from the cmake GUI. At my top level CMakeLists.txt, I have this:

option(USE_STATIC_BOOST "Build with static BOOST libraries instead of dynamic" NO) 

Then in another file, I have the following logic installed:

 if(USE_STATIC_BOOST) unset(Boost_LIBRARIES) message(WARNING "Linking against boost static libraries") set(Boost_USE_STATIC_LIBS ON) set(Boost_USE_MULTITHREADED ON) find_package(Boost REQUIRED COMPONENTS thread program_options system) else(USE_STATIC_BOOST) unset(Boost_LIBRARIES) message(WARNING "Linking against boost dynamic libraries") set(Boost_USE_STATIC_LIBS OFF) set(Boost_USE_MULTITHREADED ON) find_package(Boost REQUIRED COMPONENTS thread program_options system) endif(USE_STATIC_BOOST) 

This seems to be fine if I start from scratch and use:

 cmake ../.. -DUSE_STATIC_BOOST=YES 

However, when I use

 ccmake ../.. 

I can not get it to use static libraries no matter what I do. It seems that CMake loads the dynamic parameter into the cache at startup and changing USE_STATIC_BOOST does not switch it. I even tried disabling (Boost_LIBRARIES) to explicitly clear it. Is there a way to do what I'm trying to do?

Using x86_64 Linux and g ++ for compilation. Thanks in advance!

+7
source share
1 answer

To force the FindBoost CMake module to search for the necessary libraries again , you need to clear the Boost_INCLUDE_DIR and Boost_LIBRARY_DIRS cache variables, i.e.

 set(Boost_USE_STATIC_LIBS ${USE_STATIC_BOOST}) set(Boost_USE_MULTITHREADED ON) unset(Boost_INCLUDE_DIR CACHE) unset(Boost_LIBRARY_DIRS CACHE) find_package(Boost REQUIRED COMPONENTS thread program_options system) if(USE_STATIC_BOOST) message(STATUS "Linking against boost static libraries") else(USE_STATIC_BOOST) message(STATUS "Linking against boost dynamic libraries") endif(USE_STATIC_BOOST) 

Note that the CACHE argument is required for the unset command to clear cache variables.

Also note that after the USE_STATIC_BOOST parameter variable USE_STATIC_BOOST been cached, you need to explicitly set the variable from the command line or edit the value in the cache file so that CMake notices this change:

 cmake ../.. -DUSE_STATIC_BOOST=NO 
+12
source

Source: https://habr.com/ru/post/921442/


All Articles