使用boost的thread库

1. test.cpp内容如下

#include <boost/thread.hpp>

void hello()

{

  std::cout << "i am a hello thread" << std::endl;

}

int main(void)

{

  boost::thread _thread(hello);

  _thread.join();

  getchar();

  return 0;

}

 

2. g++编译

a. 动态链接

  我的boost装在/usr/xt/boost_1_53_0,所以编译指令如下

g++  test.cpp  -o test_dynamic  -L usr/xt/boost_1_53_0  -L usr/xt/boost_1_53_0/stage/lib   -lboost_thread

  编译,却发现链接错误,提示

undefined reference to 'boost::system::generic_category()'

  应该是少了boost_system库,于是改成这样

g++  test.cpp  -o test_dynamic  -L usr/xt/boost_1_53_0  -L usr/xt/boost_1_53_0/stage/lib   -lboost_thread -boost_system

  编译成功。

b. 静态链接

  编译指令如下

g++  test.cpp  -o test_static  -L usr/xt/boost_1_53_0  -L usr/xt/boost_1_53_0/stage/lib   -lboost_thread -boost_system -static

  编译,N多的链接错误,主要的提示是

undefined reference to 'pthread_xxx'

  应该是少了pthread库,于是指令改成这样

g++  test.cpp  -o test_static  -L usr/xt/boost_1_53_0  -L usr/xt/boost_1_53_0/stage/lib   -lboost_thread -boost_system  -lpthread -static

  编译,还是有几个链接错误,提示:

undefined reference to 'clock_gettime'

  这是少了rt库,指令再次改成这样

g++  test.cpp  -o test_static  -I /usr/xt/boost_1_53_0  -L /usr/xt/boost_1_53_0/stage/lib   -lboost_thread -lboost_system  -lpthread -lrt -static

  编程,成功。

  注意:-lpthread -lrt 必须放在 -lboost_thread -lboost_system 后面,不知道为啥。。。

 

3. 使用Makefile编译

  makefile如下,其中 testB.h 和 testB.cpp 是我加的一个测试类,只是用来测试多文件写makefile

CXXFLAGS =    -O2 -g -Wall -fmessage-length=0

CC =         g++

OBJS =        test.o testB.o

INCLUDES =    /usr/xt/boost_1_53_0

LIBS =        /usr/xt/boost_1_53_0/stage/lib

TARGET =    test



$(TARGET):    $(OBJS)
    $(CC)    $(OBJS) -o $(TARGET) -L $(LIBS) -lboost_system -lboost_thread -lpthread -lrt -static


all:    $(TARGET)

testB.o:        testB.cpp testB.h
    $(CC)    testB.cpp -c $(CXXFLAGS)

test.o:    test.cpp testB.h
    $(CC)    test.cpp -c -I$(INCLUDES) $(CXXFLAGS)

clean:
    rm -f $(OBJS) $(TARGET)

 

posted @ 2013-05-04 23:19  啊饭  阅读(1902)  评论(0编辑  收藏  举报