linux c 静态连接,Linux cmake 静态链接boost

66b52468c121889b900d4956032f1009.png

8种机械键盘轴体对比

本人程序员,要买一个写代码的键盘,请问红轴和茶轴怎么选?

背景

使用动态链接编译的二进制程序在执行时要求开发环境与生产环境严格一致,因此我们更倾向于使用静态链接的方式链接第三方库。本文介绍如何在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: [email protected]

> Created Time: 2018-06-05 16:02:08

************************************************************************/

#include

#include

#include

// test boost split

#include

// include other boost header file you need.

int main()

{

std::string s("1;2;3;4");

std::vector<: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.txtcmake_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

执行结果如下

e2cdb4a7152ae2ec9dab9bd4d9f97551.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值