关于boost的编译可查看本人的另外一篇文章:Linux上编译boost1.49
现编写一个简单的程序:
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <string>
#include <iostream>
int main()
{
//用lexical_cast来测试是否可以正常使用无需链接库的boost
using boost::lexical_cast;
int a = lexical_cast<int>("123");
double b = lexical_cast<double>("123.12");
std::cout<<a<<std::endl;
std::cout<<b<<std::endl;
//用regex来测试是否可以正常使用需要链接库的boost
std::string s = "who,lives:in-a,pineapple under the sea?";
boost::regex re(",|:|-|\\s+");
boost::sregex_token_iterator p(s.begin( ), s.end( ), re, -1);
boost::sregex_token_iterator end;
while (p != end) std::cout << *p++ << '\n';
return 0;
}
假设代码保存为test.cpp,现在些makefile:
ROOTPATH = /home/xyz
IBOOST = $(ROOTPATH)/boost_1_49_0
INLUDEPATH = -I $(IBOOST)
LBOOST = $(ROOTPATH)/boost_1_49_0/stage/lib
LIBPATH = -L $(LBOOST)
#为了方便,可以将以上内容保存为一个单独的makefile,假设叫做base_settings
#然后在各个具体的makefile中用下面的方式进行引用(引用是要去掉前面的#):
#include somepath/base_settings
#指定输出名为test.exe,当然,你也可以指定为其他任何合法的名称
test.exe : test.o
c++ -o test.exe test.o $(INLUDEPATH) $(LIBPATH) -lboost_regex-gcc44-mt-d-1_49
test.o : test.cpp
c++ -c test.cpp -g $(INLUDEPATH)
clean :
rm test.exe test.o
保存为makefile(注意保存的格式,三个绿色的地方,需要在前面加一个Tab字符),就可以正常编译了。注意,上面指定库的方式:-lboost_regex-gcc44-mt-d-1_49,并没有lib前缀和.so后缀。
如果要使用静态库,可以添加-static参数:
c++ -o test.exe test.o $(INLUDEPATH) $(LIBPATH) -Wl,-Bstatic -lboost_regex-gcc44-mt-sd-1_49 -Wl,-Bdynamic
注意,首先用-Wl,-Bstatic指定使用静态链接方式链接boost_regex-gcc44-mt-sd-1_49(此时库自动对应为libboost_regex-gcc44-mt-sd-1_49.a);
然后,立即恢复为动态链接-Wl,-Bdynamic。如果不恢复的话,ld将继续使用静态链接的方式链接c库,std库等,这将引发一大堆错误。
在使用链接库的过程中,如果发生了undefined reference to的错误,说明是链接时出错。
根本原因是ld找不到所指定的库:
首先检查指定的库名是否正确;
其次检查库路径是否正确。
然后,确保链接库和链接对象匹配(如,在上面的例子中,链接程序需要将test.o和libboost_regex-gcc44-mt-d-1_49.so进行链接,以产生最终的test.exe。如果你不小心将 $(LIBPATH) -lboost_regex-gcc44-mt-d-1_49这些参数指定给了下面的test.o : test.cpp,就会发生undefined reference to的错误)。
最后,确保链接库的依赖顺序正确。