到Boost官网下载 boost_1_69_0.zip
把下载的
boost_1_69_0.zip
解压到E:\source\boost_1_69_0
下;
执行其下的脚本文件
bootstrap.bat
,它会把复制windows下的编译环境的工具bjam.exe
复制此目录下.
下面以program_options库为例, 其需要的编译命令如下:
bjam install --prefix="D:\libraries\boost" debug release link=static runtime-link=static threading=multi address-model=32 --with-program_options
※对于Boost库,最好是用到什么库再编译,否则编译时间需要很长
上面的命令执行完后,就会把生成的库文件复制到prefix指定的路径.
cmake_minimum_required(VERSION 2.8)project(HelloBoost)find_package(Boost REQUIRED COMPONENTS program_options)include_directories(${Boost_INCLUDE_DIR})link_directories(${Boost_LIBRARY_DIRS})FILE(GLOB SC *.cpp)add_executable(${PROJECT_NAME} ${SC})
调用find_package()查找Boost库及导入其子库program_options, 另还需要向工具导入头文件与库文件所在的路径.
#include <boost/program_options.hpp>namespace po = boost::program_options;#include <iostream>using namespace std;int main(int argc, char** argv){ int compression = -1; po::options_description desc("Allow options"); desc.add_options() ("help,h", "produce help message") ("compression,c", po::value<int>(&compression)->default_value(0), "set compression level"); po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); } catch (std::exception& ex) { std::cout << ex.what() << std::endl; return 0; } if (vm.count("help")) { cout << desc << endl; return 1; } if (vm.count("compression")) { cout << "Compression level was set to " << compression << endl; } else { cout << "Compression level was not set." << endl; } return 0;}
add_options()后中的
po::value<int>(&compression)
作用是把命令行参数绑定及直接赋值到临时变量compression;
另default_value(0)
为参数设置默认值,若不设置默认值则会强制参数为必填项.