一、安裝boost庫
sudo apt-get install libboost-dev
aptitude search boost
二、編寫測試代碼
1 #include <iostream> 2 #include <string> 3 #include <boost/program_options.hpp> 4 5 namespace bpo = boost::program_options; 6 using namespace std; 7 8 int main(int argc, char const *argv[]) 9 { 10 //步驟1:構造選項描述器 11 //選項描述起,其參數為該描述器名字 12 bpo::options_description opts("all options"); 13 //選項存儲器,繼承自map容器 14 bpo::variables_map vm; 15 16 //步驟2:為選項描述器增加選項 17 //其參數依次為:key,value的類型,該選項描述 18 opts.add_options() 19 ("filename", bpo::value<std::string>(), "the file name which want to be found") 20 ("help", "this is a program to find a specified file"); 21 22 //步驟3:先對命令行輸入的參數做解析,而后將其存入選項存儲器 23 //如果輸入了未定義的選項,程序會拋出異常,所以對解析代碼要用try-catch塊包圍 24 try { 25 //parse_command_line()對輸入的選項做解析 26 //store()將解析后的結果存入選項存儲器 27 bpo::store(bpo::parse_command_line(argc, argv, opts), vm); 28 } catch(...) { 29 std::cout<<"Input option not exsited."<<std::endl; 30 return 0; 31 } 32 33 //步驟4:參數解析完畢,處理實際信息 34 //count()檢測該選項是否被輸入 35 if(vm.count("help")) { //若參數中有help選項 36 //options_description對象支持流輸出,會自動打印所有的選項信息 37 std::cout<<opts<<std::endl; 38 } 39 if(vm.count("filename")) { 40 //variables_map(選項存儲器)是std::map的派生類,可以像關聯容器一樣使用, 41 //通過operator[]來取出其中的元素,但其內部的元素類型value_type是boost::any, 42 //用來存儲不確定類型的參數值,必須通過模版成員函數as<type>()做類型轉換后, 43 //才能獲取其具體值 44 std::cout<<"find"<<vm["filename"].as<std::string>()<<std::endl; 45 } 46 if(vm.empty()) { 47 std::cout<<"no options found"<<std::endl; 48 } 49 return 0; 50 }
編譯時要加上庫名字:
g++ -o s main.cpp -lboost_program_options
使用效果:
pi@raspberrypi:~/chen_DIR/weihua/myoptions $ ./s --help all options: --filename arg the file name which want to be found --help this is a program to find a specified file pi@raspberrypi:~/chen_DIR/weihua/myoptions $ ./s --filename s finds