Boost 编译及boost::thread静态链接使用

本文介绍Boost库1.49版本的下载、编译过程及线程功能的测试代码实现。提供了动态和静态链接的编译指令,并特别说明了静态编译时必须指定-lpthread参数的原因。

1)源码下载

由于项目需要,准备移植到Android平台上,所以下载了1.49版本boost库,鉴于浏览器速度缓慢,

建议获取到下载链接,使用迅雷下载,服务器上有缓存的!!

下载链接如下:

http://nbtelecom.dl.sourceforge.net/project/boost/boost/1.49.0/boost_1_49_0.tar.bz2


2)编译

解压省略,静态编译,无需安装

#cd boost_1_49_0

#./bootstrap.sh     (后面添加--prefix=dir可以指定安装的目录,默认安装到/usr/local)

#./b2 (后面添加install将库安装到系统目录下)



3)测试代码:

#include <boost/thread.hpp>

#include <iostream>


void task1() { 

    // do stuff

    std::cout << "This is task1!" << std::endl;

}


void task2() { 

    // do stuff

    std::cout << "This is task2!" << std::endl;

}


int main (int argc, char ** argv) {

    using namespace boost; 

    thread thread_1 = thread(task1);

    thread thread_2 = thread(task2);


    // do other stuff

    thread_2.join();

    thread_1.join();

    return 0;

}



4)编译


动态链接:


使用安装目录:

g++ test.cpp -I /usr/local/include/boost/ -L  /usr/local/lib/ -lboost_thread  -o example


使用原有的生成目录

g++ test.cpp -I /home/boost/boost_1_49_0/boost -L /home/boost/boost_1_49_0/stage/lib/ -lboost_thread -o example


静态链接:


使用安装目录:

g++ test.cpp -I /usr/local/include/boost/ /usr/local/lib/libboost_thread.a -lpthread -o example



使用已有的目录:

g++ test.cpp -I /home/boost/boost_1_49_0/boost  /home/boost/boost_1_49_0/stage/lib/libboost_thread.a -lpthread  -o example



注意作为静态编译必须指定-lpthread,原因在于libboost_thread.so静态库在进行静态链接的时候必须指定POSIX线程库,否则无法找到pthread函数库的函数实现,就会出现函数调用的未定义异常,简单截取

其中的错误如下:

undefined reference to `pthread_setspecific'

undefined reference to `pthread_key_create'



参考:

http://blog.youkuaiyun.com/lixinneo/article/details/7679996






     本文转自fengyuzaitu 51CTO博客,原文链接:http://blog.51cto.com/fengyuzaitu/1394733,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值