Ubuntu下添加boost庫

@Ubuntu下Boost庫的鏈接

在CmakeLists.txt中添加Boost組件

Boost具有很好的平臺獨立性,因此可以作爲首選api來完成特定功能。

最常用的爲filesystem,用來獲取程序的運行目錄

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operation.hpp>

但是經常編譯的時候會提示如下錯誤:

undefined reference to `boost::system::generic_category()'
undefined reference to `boost::system::system_category()'
.text._ZN5boost10filesystem12initial_pathEv[_ZN5boost10filesystem12initial_pathEv]+0x19): undefined reference to `boost::filesystem::detail::initial_path(boost::system::error_code*)'

有時也會提示:

Dso missing from command line

針對Boost,這種情況一般都是相應的庫沒有被正確的鏈接,BOOST的鏈接可以用以下兩種方法:

用find_package
find_package(Boost REQUIRED COMPONENTS
filesystem   
#這裏只使用了一個組件filesystem,如果想要找所有的Boost包含的庫,直接find_package(Boost REQUIRED)
)
if(NOT Boost_FOUND)
    message("Not found Boost")
endif()

include_directories(${Boost_INCLUDE_DIRS}) #包含Boost的頭文件
add_executable( exe_name src/process_template.cpp ) #創建可執行文件,即用該cpp文件生成可執行文件
target_link_libraries(process ${Boost_LIBRARIES})  #將Boost庫鏈接到該可執行文件
#可以使用message查看一下find_package找的庫或者頭文件的位置
message("${Boost_INCLUDE_DIRS}")
message("${Boost_LIBRARIES}")
用set進行設置

就如上面所說,如果find_package找到的不是我們想要的版本,這是可以直接去指定Boost的find文件所對應的位置,同時也可以直接設定Boost_INCLUDE_DIRS,Boost_LIBRARIES 的位置:
例如我的boost頭文件保存在/usr/include中,
對應的庫文件在 /usr/lib/x86_64-linux-gnu中,則可以做如下設定:

set(Boost_INCLUDE_DIRS "/usr/include")
set(Boost_LIBRARIES " /usr/lib/x86_64-linux-gnu")
include_directories(${Boost_INCLUDE_DIRS})
add_executable( exe_name src/process_template.cpp )
#在庫鏈接時可以與之前一樣鏈接${Boost_LIBRARY},也可以鏈接指定的庫
target_link_libraries(process libboost_filesystem.so libboost_system.so )

常用的組件就是filesystem和system兩個部分;
同時foreach組件也會用到,主要是用於對循環程序結構的編譯器級別實現,不依賴高級別的編譯器,即再低級別的便一起上也能夠運行編譯;
具體的使用方法如下:

#include <boost/foreach.hpp> //包含對應的頭文件
BOOST_FOREACH(rosbag::MessageInstance const m, view){
#這裏使用的讀取RODBAG中的數據,與for循環的功能類似
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章