【錯誤】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,添加幾個:

       #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方式,如果不知道,可以使用第二種。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM