在 Windows 上将 Boost_USE_STATIC_LIB OFF 链接 boost 库

Linking boost library with Boost_USE_STATIC_LIB OFF on Windows

我的 CMakeFiles.txt 看起来像这样:

cmake_minimum_required ( VERSION 2.6 )

# Set warnings on and enable debugging
SET( CMAKE_C_FLAGS "-Wall -q" )

include(FindBoost)

set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)

find_package( Boost 1.57.0 COMPONENTS system filesystem REQUIRED )

if( Boost_FOUND )
    message( STATUS "Boost found!" )
    include_directories(${Boost_INCLUDE_DIRS})
    add_executable(foo main.cpp)

    # Needed for asio
    if(WIN32)
      target_link_libraries(foo wsock32 ws2_32)
    endif()

    target_link_libraries(foo ${Boost_LIBRARIES})
endif()

我为 Visual Studio 2013 64 位渲染项目:

cmake -G "Visual Studio 12 Win64" -DBOOST_LIBRARYDIR=D:\Development\Tools\boost_1_57_0\stage\x64\lib ..\KServer

输出为:

-- The C compiler identification is MSVC 18.0.31101.0
-- The CXX compiler identification is MSVC 18.0.31101.0
-- Check for working C compiler using: Visual Studio 12 2013 Win64
-- Check for working C compiler using: Visual Studio 12 2013 Win64 -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler using: Visual Studio 12 2013 Win64
-- Check for working CXX compiler using: Visual Studio 12 2013 Win64 -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Boost version: 1.57.0
-- Boost version: 1.57.0
-- Found the following Boost libraries:
--   system
--   filesystem
-- Boost found!
-- Configuring done
-- Generating done
-- Build files have been written to: D:/Development/Private/C++/KServerProject

一切都很好。

问题从这里开始:

当我更改我的 cmake 文件以使用时:

set(Boost_USE_STATIC_LIBS OFF)

然后我在构建时 Visual Studio 中出现以下错误:

error LNK1104: cannot open file 'libboost_filesystem-vc120-mt-gd-1_57.lib'  D:\Development\Private\C++\KServerProject\src\LINK  foo

检查工作室中的 Property Pages 库已添加为依赖项:

将文件夹 D:\Development\Tools\boost_1_57_0\stage\x64\lib 手动添加到 Additional Library Directories 时,构建正常。

如何使用动态库创建项目?

我相信你需要添加

add_definitions( -DBOOST_ALL_NO_LIB )

参见http://www.boost.org/doc/libs/1_57_0/libs/config/doc/html/index.html。我在我的 CMakeLists.txt 中设置了它,它适用于我的 visual studio 使用 boost 构建。作为测试,我删除了它并得到了与您相同的错误。

对于它的价值,这里是我如何将 boost 与 cmake 一起使用。

# boost
set(Boost_NO_SYSTEM_PATHS true)
set (Boost_USE_STATIC_LIBS OFF CACHE BOOL "use static libraries from Boost")
set (Boost_USE_MULTITHREADED ON)
find_package(Boost REQUIRED 
  COMPONENTS
  system program_options thread filesystem
  date_time chrono timer regex serialization
  )
include_directories(${Boost_INCLUDE_DIRS})
link_libraries(${Boost_LIBRARIES})

if (WIN32)
  # disable autolinking in boost
  add_definitions( -DBOOST_ALL_NO_LIB )

  # force all boost libraries to dynamic link (we already disabled
  # autolinking, so I don't know why we need this, but we do!)
  add_definitions( -DBOOST_ALL_DYN_LINK )
endif()