Search code examples
c++visual-studiocmakeboostvisual-studio-2022

How do I link compiled Boost binaries in Visual Studio 2022 through CMake?


I have downloaded Boost in my D:\ (not the default path) and generated all binaries using

.\b2 -j4 link=static threading=multi runtime-link=shared --build-type=minimal stage --stagedir=stage/

Then I created a simple Visual Studio 2022 project using CMake. The content of the CMakeLists.txt is:

cmake_minimum_required (VERSION 3.12)

# Enable Hot Reload for MSVC compilers if supported.
if (POLICY CMP0141)
  cmake_policy(SET CMP0141 NEW)
  set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT "$<IF:$<AND:$<C_COMPILER_ID:MSVC>,$<CXX_COMPILER_ID:MSVC>>,$<$<CONFIG:Debug,RelWithDebInfo>:EditAndContinue>,$<$<CONFIG:Debug,RelWithDebInfo>:ProgramDatabase>>")
endif()


set(BOOST_ROOT D:/boost_1_82_0)
set(Boost_INCLUDE_DIR ${BOOST_ROOT})
set(Boost_DEBUG ON)
set(Boost_NO_SYSTEM_PATHS TRUE)
set(Boost_NO_BOOST_CMAKE TRUE)
# set(Boost_USE_STATIC_LIBS_ON)
find_package(Boost REQUIRED)
include_directories(${Boost_INCLUDE_DIR})

project ("HelloCMake")

# Add source to this project's executable.
add_executable (HelloCMake "HelloCMake.cpp" "HelloCMake.h")

message(boost_libraries "${Boost_LIBRARIES}")
target_link_libraries(HelloCMake ${Boost_SYSTEM_LIBRARY} ${Boost_FILESYSTEM_LIBRARY} ${Boost_CONTAINER_LIBRARY})

It runs fine as long as it needs only the headers like boost::asio but as soon as I added any of the header files which requires compiled binaries like boost/json/src.hpp Visual Studio fails to link and gives the error Error LNK1104 cannot open file 'libboost_container-vc143-mt-gd-x64-1_82.lib'

I am new to cmake so I might be missing something obvious. Do you see any error with the cmake config? Thanks!


Solution

  • The solution is to disable auto-linking. The additional config that I needed was:

       # disable autolinking in boost
       add_definitions( -DBOOST_ALL_NO_LIB )
    
       # we already disabled autolinking, but we need this for intellisense errors to go away.
       # without this option VS will keep on complaining about boost libs not found but it will run successfully.
       add_definitions( -DBOOST_ALL_DYN_LINK )