使用 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
分类:
C/C++
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!