使用 Google gflags 简化命令行参数处理
(本文章仅适用于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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步