简体   繁体   English

如何使用CMake选择性地链接静态或动态boost库?

[英]How can I optionally link against static or dynamic boost library using CMake?

I have a CMake project that I sometimes want to compile against the static boost libraries, but I want to also make it easy to just use the dynamic libraries from the cmake GUI. 我有一个CMake项目,我有时想要针对静态boost库进行编译,但我还希望能够轻松地使用cmake GUI中的动态库。 In my top level CMakeLists.txt I have this: 在我的顶级CMakeLists.txt我有这个:

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

Then in a different file, I have the following logic set up: 然后在另一个文件中,我设置了以下逻辑:

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 work fine if I start from scratch and use: 如果我从头开始使用,这似乎工作正常:

cmake ../.. -DUSE_STATIC_BOOST=YES

However, when I use 但是,当我使用时

ccmake ../..

I cannot get it to use the static libraries no matter what I do. 无论我做什么,我都无法使用静态库。 CMake appears to load the dynamic option into cache on startup and changing USE_STATIC_BOOST doesn't switch it. CMake似乎在启动时将动态选项加载到缓存中,并且更改USE_STATIC_BOOST不会切换它。 I even tried to unset(Boost_LIBRARIES) to explicitly clear it out. 我甚至试图取消设置(Boost_LIBRARIES)以明确清除它。 Is there a way to do what I'm trying to do? 有没有办法做我想做的事情?

Using x86_64 Linux and g++ to compile. 使用x86_64 Linux和g ++进行编译。 Thanks in advance! 提前致谢!

To force the FindBoost CMake module to search for the desired libraries again, you have to clear the cache variables Boost_INCLUDE_DIR and Boost_LIBRARY_DIRS , ie: 要强制FindBoost CMake模块再次搜索所需的库,您必须清除缓存变量Boost_INCLUDE_DIRBoost_LIBRARY_DIRS ,即:

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()
   message(STATUS "Linking against boost dynamic libraries")
endif()

Note that the argument CACHE is necessary to make the unset command clear the variables in the cache. 请注意,参数CACHE是使unset命令清除缓存中的变量所必需的。

Also note that once the option variable USE_STATIC_BOOST has been cached, you need to explicitly set the variable from the command line or edit the value in the cache file to make CMake notice the change: 另请注意,一旦缓存了选项变量USE_STATIC_BOOST ,您需要从命令行显式设置变量或编辑缓存文件中的值以使CMake注意到更改:

cmake ../.. -DUSE_STATIC_BOOST=NO 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM