动态链接提升与Cmake

时间:2016-07-19 18:48:47

标签: boost linker cmake dynamic-linking

我已经检查了几个问题,但没有一个答案有助于我的案例。这是我检查的那些

How to link C++ program with Boost using CMake

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

Error linking Boost with CMake

我用

构建了Boost 1.61
b2 variant=debug,release link=static,shared threading=single,multi

在stage / lib下,我有所有的dll和libs。在Boost :: System之后,libs存在于stage / lib

之下
boost_system-vc140-mt-1_61.dll
boost_system-vc140-mt-1_61.lib
boost_system-vc140-mt-gd-1_61.dll
boost_system-vc140-mt-gd-1_61.lib
libboost_system-vc140-mt-1_61.lib
libboost_system-vc140-mt-gd-1_61.lib

我想编译一个基本的boost asio示例(需要来自boost的系统库)。我在windows中用cmake-gui制作我的cmake文件,然后生成VS2015项目文件。尝试构建项目后,发生以下错误。

1>------ Build started: Project: ZERO_CHECK, Configuration: Debug Win32 ------
2>------ Build started: Project: boost-asio, Configuration: Debug Win32 ------
2>  main.cpp
2>  Please define _WIN32_WINNT or _WIN32_WINDOWS appropriately. For example:
2>  - add -D_WIN32_WINNT=0x0501 to the compiler command line; or
2>  - add _WIN32_WINNT=0x0501 to your project's Preprocessor Definitions.
2>  Assuming _WIN32_WINNT=0x0501 (i.e. Windows XP target).
2>LINK : fatal error LNK1104: cannot open file 'libboost_system-vc140-mt-gd-1_61.lib'
========== Build: 1 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

我的CMakeLists.txt的内容

cmake_minimum_required(VERSION 3.6)

project(boost-asio)

find_package(Boost 1.61.0 COMPONENTS system REQUIRED)

# set cmake variables
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/bin)
set(Boost_USE_STATIC_LIBS OFF)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)

# definitions
add_definitions(-DBOOST_LOG_DYN_LINK=1)

# set sources
set(SOURCES src/main.cpp)


# manage compilation and linkage
if(Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIRS})
    add_executable(boost-asio ${SOURCES})
    target_link_libraries(boost-asio ${Boost_LIBRARIES})

    message(${Boost_INCLUDE_DIRS})
    message(${Boost_LIBRARIES})
endif()

请注意,cmake源中的定义是根据我检查过的某些问题的答案添加的。 FindBoost找到了boost库,这里是cmake-gui的输出

Boost version: 1.61.0
Found the following Boost libraries:
  system
C:/Boost/boost_1_61_0
optimizedC:/Boost/boost_1_61_0/stage/lib/boost_system-vc140-mt-1_61.libdebugC:/Boost/boost_1_61_0/stage/lib/boost_system-vc140-mt-gd-1_61.lib

现在这里有两个问题。首先,它找不到库,其次,虽然它明确指示链接器动态链接,但它仍然寻找静态库。我不知道这些问题是否相关。如何解决这个问题呢?如何使用Cmake动态链接Boost?

EDIT1 :这是我正在使用的代码,如果你想测试一下。

#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

int main() {

    boost::asio::io_service ioservice;

    boost::asio::deadline_timer t(ioservice, boost::posix_time::seconds(5));

    t.wait();

    std::cout << "Hello, world!" << std::endl;

    return 0;
}

1 个答案:

答案 0 :(得分:1)

在CMakeLists.txt中添加以下标志可以解决问题:

add_definitions( -DBOOST_ALL_NO_LIB )
add_definitions( -DBOOST_ALL_DYN_LINK )