Whats the proper way to link Boost with CMake and

2019-04-09 01:24发布

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?

2条回答
做个烂人
2楼-- · 2019-04-09 02:02

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} )  
查看更多
够拽才男人
3楼-- · 2019-04-09 02:05

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

But this doesn't seem to generate static libs.

Building the special stage target places Boost library binaries in the stage\lib\ subdirectory of the Boost tree. More about building Boost on Windows here

CMake:

SET (CMAKE_BUILD_TYPE Debug) # in order to link with boost debug libs you may need to set that to build your program in debug mode (or do that from command line)

FIND_PACKAGE (Boost 1.58 COMPONENTS "chrono" "regex" "thread" REQUIRED)

#ADD_DEFINITIONS(-DBOOST_ALL_DYN_LINK) # make sure you don't have this as it will try to link with boost .dll's

INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS})
LINK_DIRECTORIES(${Boost_LIBRARY_DIRS})

TARGET_LINK_LIBRARIES(${EXE_OR_LIB_NAME} ${Boost_LIBRARIES})
查看更多
登录 后发表回答