Boost 是 C++ 的一个增强库,可以看做 std 的扩展。在 Windows 上编译安装很简单。
首先下载代码包:https://www.boost.org/users/history/ 并解压,使用 Visual Studio 提供的 x64 兼容命令提示符工具进入源码目录,运行目录下的 bootstrap.bat 脚本,目录下将出现 bjam.exe 与 b2.exe 等文件。之后即可使用 bjam 工具编译。
实际上 Boost 库的绝大多数组件都是 header-only 的,也就是无需进一步编译生成可执行文件,只需要引入头文件即可,但是以下几个组件除外:
- Boost.Chrono
- Boost.Context
- Boost.Filesystem
- Boost.GraphParallel
- Boost.IOStreams
- Boost.Locale
- Boost.Log
- Boost.MPI
- Boost.ProgramOptions
- Boost.Python
- Boost.Regex
- Boost.Serialization
- Boost.Signals
- Boost.System
- Boost.Thread
- Boost.Timer
- Boost.Wave
它们需要在编译时用 --with-
参数单独指定。编译命令如下:
bjam stage --prefix="C:\Dev\Boost\build" --with-regex --with-system --with-thread address-model=64 --build-type=complete debug release install
编译为 64 位版本,并指定了附加编译 Boost.Regex(正则),Boost.System,Boost.Thread 几个库。其中 --prefix 为生成的头文件与库存放的目录,可以自行更改。
完成后对应目录下会出现 include 与 lib 两个文件夹,将 include/boost-xxx 添加到 VS 的包含目录, lib 添加到库目录,VS 编译项目时会自动搜索链接库。
测试代码(正则表达式匹配邮件主题):
#include <boost/regex.hpp>
#include <iostream>
#include <string>
int main()
{
std::string line;
boost::regex pat( "^Subject: (Re: |Aw: )*(.*)" );
while (std::cin)
{
std::getline(std::cin, line);
boost::smatch matches;
if (boost::regex_match(line, matches, pat))
std::cout << matches[2] << std::endl;
}
}
然后将以下内容保存为 text.txt:
To: George Shmidlap
From: Rita Marlowe
Subject: Will Success Spoil Rock Hunter?
---
See subject.
在 CMD 中测试:
text.exe < test.txt
输出:
Will Success Spoil Rock Hunter?
以上。