(1)首先下载源代码:http://www.boost.org/users/download/ 解压到某个目录:E:\CodeDLL\boost_1_64_0
(2)生成bjam.exe可执行文件,用管理员权限运行VS2010命令窗口
进入到到目录E:\CodeDLL\boost_1_64_0,运行booststrap.bat得到:
这时在目录E:\CodeDLL\boost_1_64_0,生成了b2.exe、bjam.exe、project-config.jam文件。
(3)用bjam.exe编译
运行命令
编译静态库如下.
bjam stage --toolset=msvc-10.0 --without-python --build-type=complete --stagedir="E:\CodeDLL\boost_1_64_0\bin\vc10" link=static runtime-link=shared threading=multi debug release
编译动态库如下.
bjam stage --toolset=msvc-10.0 --without-python --build-type=complete --stagedir="E:\CodeDLL\boost_1_64_0\bin\vc10" link=shared runtime-link=shared threading=multi debug release
bjam可以参考http://blog.chinaunix.net/uid-22301538-id-3158997.html
stage表示只生成库(dll和lib),用install的话还会生成包含头文件的include目录。
toolset指定编译器,VS2010用msvc-10.0。
without/with表示不编译/编译哪些库。
stagedir,当使用stage时用stagedir,使用install用prefix,表示编译生成文件的路径。路径的命名最好和编译器相关,编译管理。
link指定生成动态链接库或静态链接库。生成动态链接库需使用shared方式,生成静态链接库需使用static方式。
runtime-link,动态/静态链接C/C++运行时库。有shared和static两种方式,这样runtime-link和link一共可以产生4种组合方式。
threading,单/多线程编译。
debug/release,编译debug/release版本。一般都是程序的debug版本对应库的debug版本,所以两个都编译。
Bjam参数说明
--build-dir= 编译的临时文件会放在builddir里(这样比较好管理,编译完就可以把它删除了)
--stagedir= 存放编译后库文件的路径,默认是stage
--build-type=complete 编译所有版本,不然只会编译一小部分版本(确切地说是相当于:variant=release, threading=multi;link=shared|static;runtime-link=shared)
variant=debug|release 决定编译什么版本(Debug or Release?)
link=static|shared 决定使用静态库还是动态库。
threading=single|multi 决定使用单线程还是多线程库。
runtime-link=static|shared 决定是静态还是动态链接C/C++标准库。
--with- 只编译指定的库,如输入
--with-regex就只编译regex库了。
--show-libraries 显示需要编译的库名称
编译全部bjam --toolset=msvc --build-dir=midfiles --stagedir=stage --build-type=complete
只编译线程库bjam --toolset=msvc --build-dir=midfiles --stagedir=stage --build-type=complete --with-thread
差不多需要一小时,编译完成(中间会有警告)。
编译好后,在根目录会有个bin.v2文件夹,是编译过程中的临时文件夹,很大,可以手动删除。
(4)在VS中使用Boost库
新建工程后需要把Boost库包含到工程中,右键选择属性,在VC++目录的“包含目录”中添加Boost的根目录,在“库目录”添加刚刚编译生成的位置再加上路径lib。
使用举例:
#include <boost/thread.hpp> |
此时,不用包含库文件,boost的auto-link机制将会自动帮我们包含对应的静态lib。也就是说,boost默认是以静态方式链接的,这样我们的工程属性最好也设为Multi-threaded (Debug)。如果想使用dll动态方式链接,需要预先定义宏:
#define BOOST_ALL_DYN_LINK |
同样,此时boost也会默认帮我们包含对应的lib。如果不想使用boost提供的auto-link机制,或者对它的自动链接不太放心的话(其实大可不必担心),可以预先定义宏:
#define BOOST_ALL_NO_LIB |
然后使用以下方法链接:
Release下
#pragma comment(lib, "boost_thread-vc100-mt-1_64.lib") |
#pragma comment(lib, "boost_thread-vc100-mt-gd-1_64.lib") |
另外还有一个比较有用的宏:
#define BOOST_LIB_DIAGNOSTIC |
它可以让VC在编译时的output窗口中输出程序具体链接了哪些boost库以及链接顺序。
关于boost的auto-link机制,详细可以看看boostconfigauto_link.hpp里的代码,很容易可以读懂,并且值得我们学习。
包含Boost对应库的头文件即可使用,例如一个多线程的测试:
- #include "boost/thread.hpp"
- #include "iostream"
- using namespace std;
- void threadFunc()
- {
- cout << "This is a thread function" << endl;
- }
- int main()
- {
- boost::function<void()> func(threadFunc);
- boost::thread t(func);
- t.join();
- return 0;
- }