Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the proper way to link Boost with CMake and Visual Studio in Windows?

I am trying to generate some Boost 1.58 libraries that I need (chrono, regex and thread) for Visual Studio 2012 and link the libraries with CMake. I have real problems for CMake and Visual Studio to find or link the libs, depending on the configuration I set.

I am finally using the following configuration:

bjam.exe --link=static --threading multi --variant=debug stage

But this doesn't seem to generate static libs.

How should I generate the libs and search them with CMake in order for Visual Studio to link them properly?

like image 400
Jav_Rock Avatar asked Jun 24 '15 10:06

Jav_Rock


1 Answers

I finally came up with the solution and I think it is detailed enough to become a generic answer.

Visual Studio searches for dynamic libraries so we need to compile Boost libraries as shared, multithreaded, debug and release, and runtime-link shared. In windows using bjam.exe all commands have the prefix "--" except link, so the right way to build the libraries is:

bjam.exe link=shared --threading=multi --variant=debug --variant=release --with-chrono --with-regex --with-thread stage

This will generate the libs and DLLs in the folder Boost/stage/lib, so we need to set an environment variable Boost_LIBRARY_DIR C:/Boost/stage/lib, for example.

There are more options that may come in hand:

runtime-link = shared/static
toolset= msvc-11.0

The libraries will have a name like this for release:

boost_chrono-vc110-mt-1_58.lib
boost_chrono-vc110-mt-1_58.dll

And for debug:

boost_chrono-vc110-mt-gd-1_58.lib
boost_chrono-vc110-mt-gd-1_58.dll

In order for CMake to link them properly we need to write the following in the CMakeLists.txt:

    add_definitions( -DBOOST_ALL_DYN_LINK )  //If not VS will give linking errors of redefinitions
    set(Boost_USE_STATIC_LIBS OFF )
    set(Boost_USE_MULTITHREADED ON)
    set(Boost_USE_STATIC_RUNTIME OFF)
    find_package(Boost COMPONENTS thread chrono regex REQUIRED )

    INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS})

    TARGET_LINK_LIBRARIES( ${PROJ_NAME} ${Boost_LIBRARIES} )  
like image 178
Jav_Rock Avatar answered Sep 24 '22 10:09

Jav_Rock