Windows下如何使用BOOST C++庫
我采用的是VC8.0和boost_1_35_0。自己重新編譯boost當然可以,但是我使用了
http://www.boostpro.com/products/free
提供的安裝工具 BoostPro 1.35.0 Installer (192K .exe) 。我強烈建議使用這個工具來在Windows下安裝BOOST庫和源文件。
1)使用boost_1_35_0_setup.exe這個工具下載boost庫,選擇你要的包(類型總是Mutilthread和Mutithread Debug),下載后自動安裝。我用VC8.0的boost_1_35_0安裝在E:/boost。我主要介紹用RegEx和Signals這2個需要編譯后才能使用的庫,
2)我在VC8.0下建立了一個Console工程,並為工程添加了VC包含目錄:E:/boost/boost_1_35_0,和庫目錄:E:/boost/boost_1_35_0/lib。不需要指定鏈接哪個庫,因為系統會自動查找的。
3)需要注意的是,我不使用動態鏈接庫,因為一堆的警告,讓我恐懼。因此我使用靜態的連接庫,就是名稱前有libboost-xxx樣式的庫。比如,要使用(注意與下面的名稱完全一致):
Debug下:
libboost_signals-vc80-mt-gd-1_35.lib
libboost_regex-vc80-mt-gd-1_35.lib
Release下:
libboost_signals-vc80-mt-1_35.lib
libboost_regex-vc80-mt-1_35.lib
而VC的項目屬性是:
Debug:多線程調試 DLL (/MDd),不采用Unicode
Release:多線程 DLL (/MD),不采用Unicode
尤其要注意,使用工具下載的時候,總是下載:
Mutilthread 和 Mutithread Debug
這樣的好處是,我們是鏈接到靜態的boost庫,所以,不需要任何boost的dll。不要為了貪圖小一點尺寸的運行時包而選擇使用boost的動態庫,起碼我看那一堆的警告就不寒而栗。
下面就是個小例子,沒任何警告,一切如期:
///////////////////////////////////////////////////////////////////////////////
// main.cpp
//
// 使用BOOST C++標准庫
//
//
// 2008-7-10 cheungmine
//
///////////////////////////////////////////////////////////////////////////////
#include <boost/lambda/lambda.hpp>
#include <boost/regex.hpp>
#include <iostream>
#include <cassert>
#include <boost/signals.hpp>
struct print_sum {
void operator()(int x, int y) const { std::cout << x+y << std::endl; }
};
struct print_product {
void operator()(int x, int y) const { std::cout << x*y << std::endl; }
};
//
// 主程序
//
int main(int argc, char** argv)
{
boost::signal2<void, int, int, boost::last_value<void>, std::string> sig;
sig.connect(print_sum());
sig.connect(print_product());
sig(3, 5);
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;
}
return 0;
}