【错误】undefined reference to `boost::....的解决

很多新手引用Boost库编程,在ubuntu下编译时候有时候会出现如下错误:

test04.cpp:(.text+0x2c): undefined reference to `boost::program_options::options_description::m_default_line_length'

test04.cpp:(.text+0x37): undefined reference to `boost::program_options::options_description::m_default_line_length'
test04.cpp:(.text+0x7c): undefined reference to `boost::program_options::options_description::options_description(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, unsigned int, unsigned int)'

这个问题的出现是因为使用g++编译C++项目文件时,没有链接Link上对应所需的库。解决办法有两种:

(1)在编译文件时加上配置选项

比如,一般情况下test.cpp编译时的语句为:

g++ -std=c++11 -o test.elf test.cpp 

在使用了Boost库出现上述问题时,在后面加上“-lboost_具体库名”可将编译语句改为:

g++ -std=c++11 -o test.elf test.cpp -lboost_program_options

如果报错为“undefined reference to `boost::system::…’”就可以加上-lboost_system

注释:当使用C++11标准库时需要在编译配置中加上“-std=c++11”,一半情况下使用新版的Boost都会掺杂C++11的内容,所以这个配置项最好加上。

(2)在Makefile中修改配置

如:打开Makefile找到规则

$(LINK) $(LFLAGS) -o $(TARGET) $(OBJECTS) $(OBJCOMP) $(LIBS)

修改为:

$(LINK) $(LFLAGS) -o $(TARGET) $(OBJECTS) $(OBJCOMP) $(LIBS) -lboost_system -lboost_thread

注意Makefile的格式/tab与空格是有定义区别的,而如果用QTCreator打开Makefile,保存时会以数个空格替换掉/tab,这将导致后续make不能执行,所以需要用比如Vim这样的编辑器打开修改。
3)关于#include <>
使用Boost,添加几个:

扫描二维码关注公众号,回复: 11311105 查看本文章
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/options_description.hpp>

#include ...........................

和使用1个:

#include <boost/program_options.hpp>

功能是一样的,如果能够精确知道使用的类属于哪个文件,最好使用第一种#include方式,如果不知道,可以使用第二种。

猜你喜欢

转载自blog.csdn.net/qq_41736617/article/details/106585748