静态编译boost

背景

使用动态链接编译的二进制程序在执行时要求开发环境与生产环境严格一致,因此我们更倾向于使用静态链接的方式链接第三方库。本文介绍如何在Linux 环境下使用cmake 静态链接Boost 库。

示例

我们将编译好boost静态库.a 文件和头文件放入third_party 目录,在CMakeLists.txt 中使用find_package 方法查找boost静态库。
我自己在CentOS 6.6 编译的boost 1.63.0 静态库以及头文件 boost static library

// 加入boost头文件路径
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/third_party/boost_1_63_0/include)
// 设置boost使用静态链接
set(Boost_USE_STATIC_LIBS ON)
// 设置需要的boost 组件
set(BOOST_COMPONENTS date_time chrono filesystem iostreams program_options regex system thread unit_test_framework)
// 使用cmake find_package 查找boost库位置
find_package(Boost REQUIRED COMPONENTS ${BOOST_COMPONENTS})
// 编译的bin 文件链接boost 库
TARGET_LINK_LIBRARIES(your_bin_name ${Boost_LIBRARIES})

需要注意的是,仅在CMakeLists.txt 中这样设置的话cmake find_package 无法找到boost 静态库的位置。在cmake 前加入如下参数

# 需要指定boost静态库的绝对路径
cmake -DBOOST_INCLUDEDIR=$(workspace)/third_party/boost_1_63_0/include \
      -DBOOST_LIBRARYDIR=$(workspace)/third_party/boost_1_63_0/lib ..

编译helloboost 程序静态链接boost库的完整示例如下。
helloboost.cpp

/*************************************************************************
    > File Name: helloboost.cpp
    > Author: ce39906
    > Mail: ce39906@163.com
    > Created Time: 2018-06-05 16:02:08
 ************************************************************************/
#include <iostream>
#include <string>
#include <vector>
// test boost split
#include <boost/algorithm/string.hpp>
// include other boost header file you need.

int main()
{
    std::string s("1;2;3;4");
    std::vector<std::string> v;
    std::cout << "Before boost split, size of v is " << v.size() << std::endl;
    boost::split(v, s, boost::is_any_of(";"));
    std::cout << "After boost split, size of v is " << v.size() << std::endl;
    return 0;
}

CmakeLists.txt

cmake_minimum_required(VERSION 2.6)

project(helloboost C CXX)

SET(CMAKE_CXX_FLAGS "-g -w -O2")

#default binary and lib path
SET(EXECUTABLE_OUTPUT_PATH ${CMAKE_SOURCE_DIR})
#begin to set boost static library
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/third_party/boost_1_63_0/include)
set(Boost_USE_STATIC_LIBS ON)
set(BOOST_COMPONENTS date_time chrono filesystem iostreams program_options regex system thread unit_test_framework)
find_package(Boost REQUIRED COMPONENTS ${BOOST_COMPONENTS})

ADD_EXECUTABLE(helloboost helloboost.cpp)
TARGET_LINK_LIBRARIES(helloboost ${Boost_LIBRARIES})

install.sh

#!/bin/bash
workspace=$(pwd)
mkdir -p build
cd build

cmake -DBOOST_INCLUDEDIR=${workspace}/third_party/boost_1_63_0/include \
      -DBOOST_LIBRARYDIR=${workspace}/third_party/boost_1_63_0/lib ..
make

编译并执行

./install.sh
./helloboost

执行结果如下
avatar