天天看点

Windows下如何使用BOOST C++库 .

我采用的是VC8.0和boost_1_35_0。自己重新编译boost当然可以,但是我使用了

<a href="http://www.boostpro.com/products/free">http://www.boostpro.com/products/free</a>

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 &lt;boost/lambda/lambda.hpp&gt;

#include &lt;boost/regex.hpp&gt;

#include &lt;iostream&gt;

#include &lt;cassert&gt;

#include &lt;boost/signals.hpp&gt;

struct print_sum {

 void operator()(int x, int y) const { std::cout &lt;&lt; x+y &lt;&lt; std::endl; }

};

struct print_product {

 void operator()(int x, int y) const { std::cout &lt;&lt; x*y &lt;&lt; std::endl; }

// 主程序

int main(int argc, char** argv)

{

    boost::signal2&lt;void, int, int, boost::last_value&lt;void&gt;, std::string&gt; 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 &lt;&lt; matches[2] &lt;&lt; std::endl;    

    }

    return 0;

}