(本文章僅適用於C++程序)
寫服務程序時,如果需要提供命令行參數。傳統的方法是手工解析argv參數,或者使用getopt函數。兩種方法都比較費勁。使用Google gflags可以大大簡化命令行參數處理。
寫服務程序時,如果需要提供命令行參數。傳統的方法是手工解析argv參數,或者使用getopt函數。兩種方法都比較費勁。使用Google gflags可以大大簡化命令行參數處理。
安裝gflag
從官方地址
http://code.google.com/p/google-gflags/下載gflags並安裝。比如我下載的是1.5版本。
[yichi@yichi tmp]$ wget http://google-gflags.googlecode.com/files/gflags-1.5.tar.gz[yichi@yichi tmp]$ tar zxvf gflags-1.5.tar.gz[yichi@yichi tmp]$ cd gflags[yichi@yichi gflags-1.5]$ ./configure –prefix=$HOME/google-library[yichi@yichi gflags-1.5]$ make j=4 & make install
使用gflags
main.cc
編譯示例程序
[yichi@yichi gflags-sample]$ g++ -o gflags-sample main.cc -I $HOME/google-library/include -L $HOME/google-library/lib -lgflags
運行示例程序
帶參數運行
[yichi@yichi gflags-sample]$ LD_LIBRARY_PATH=$HOME/google-library/lib:$LD_LIBRARY_PATH ./gflags-sampleServer module id:Run as daemon: 1HTTP listen port: 80HTTPS listen port: 443
帶參數運行,使用等號賦值
[yichi@yichi gflags-sample]$ LD_LIBRARY_PATH=$HOME/google-library/lib:$LD_LIBRARY_PATH ./gflags-sample -module_id="server_007" -daemon=true -http_port=8080 -https_port=4443Server module id: server_007Run as daemon: 1HTTP listen port: 8080HTTPS listen port: 4443
帶參數運行,使用空格分割參數和值
[yichi@yichi gflags-sample]$ LD_LIBRARY_PATH=$HOME/google-library/lib:$LD_LIBRARY_PATH ./gflags-sample -module_id "server_007" -daemon true -http_port 8080 -https_port 4443Server module id: server_007Run as daemon: 1HTTP listen port: 8080HTTPS listen port: 4443
顯示幫助
[yichi@yichi gflags-sample]$ LD_LIBRARY_PATH=$HOME/google-library/lib:$LD_LIBRARY_PATH ./gflags-sample –helpgflags-sample: Warning: SetUsageMessage() never calledFlags from main.cc:-daemon (If started as daemon) type: bool default: true-http_port (HTTP listen port) type: int32 default: 80-https_port (HTTPS listen port) type: int32 default: 443-memory_pool (If use memory pool) type: bool default: false-module_id (Server module id) type: string default: ""
參考資料
Google gflags官方文檔:
http://google-gflags.googlecode.com/svn/trunk/doc/gflags.html