gflags的使用教程

xiaoxiao2021-02-28  90

下载安装

下载地址 https://github.com/schuhschuh/gflags/archive/v2.1.1.tar.gz

安装

tar -xzvf gflags-2.1.1.tar.gz cd gflags-2.1.1 mkdir build cd build cmake .. -DCMAKE_INSTALL_PREFIX=/your/install/path make make install

值得注意的是,我这里新建了一个build文件夹,即采用“外部构建”的方式。这样编译过程中产生的中间文件(比如.o文件)就都放在build里,不会“污染”gflags源码,做到干干净净。

环境配置

vim ~/.bashrc export LIBRARY_PATH=/your/install/path/lib:$LIBRARY_PATH export LD_LIBRARY_PATH=/your/install/path/lib:$LD_LIBRARY_PATH source ~/.bashrc

使用步骤

头文件

#include <gflags/gflags.h>

定义参数

DEFINE_string(confPath, "../conf/setup.ini", "program configure file."); DEFINE_int32(port, 9090, "program listen port"); DEFINE_bool(daemon, true, "bool parameter"); DEFINE_double(ratio, 1.05, "double parameter");

上面三个参数分别表示:参数名称、默认值、帮助信息。

参数解析

gflags::ParseCommandLineFlags(&argc, &argv, true);//true表示不保留定义的flags

参数输出

cout << "confPath = " << FLAGS_confPath << endl; cout << "port = " << FLAGS_port << endl;

gflags的变量名是 FLAGS_我们定义的参数名。

编译运行

g++ gflags_test.cpp -o gflags_test -I/your/install/path/include -lgflags

运行是需要指定参数的,可以通过命令行和文件两种方式指定。

命令行方式

可以用 -参数名=参数值 或者 - -参数名=参数值 的方式来设定参数值。

对于bool类型的参数,除了上述方式外,还可以用 –参数名 的方式设定为true(即不带值), 使用 –no参数名 的方式设定为false。

./gflags_test -confPath="./conf/conf.ini" -port=1234 -daemon=false ./gflags_test -confPath="./conf/conf.ini" -port=1234 -daemon ./gflags_test -confPath="./conf/conf.ini" -port=1234 -nodaemon

文件参数方式

如果配置项非常多,也就是说命令行参数很多,那你每次启动都要一个一个的输入,此时就可以使用文件参数方式。

用 –flagfile=命令行文件 的方式就可以了。

./gflags_test -flagfile="./conf/flagfile.ini"

其中flagfile.ini中的内容如下:

--port=8888 --confPath=./conf/conf.ini --daemon=true

帮助和版本信息

gflags::SetVersionString("1.0.0");//设置版本,./gflag_test --version的时候会显示 gflags::SetUsageMessage("Usage: ./gflags_test");//帮助信息设置

【注意:SetVersionString() 和 SetUsageMessage() 一定要在 ParseCommandLineFlags() 之前设定。】

参数少显示帮助信息

if(argc<3) gflags::ShowUsageWithFlagsRestrict(argv[0], "gflags_test");//注意:第二个参数是限制的model_name

完整代码

#include <gflags/gflags.h> #include <iostream> #include <string> using namespace std; DEFINE_string(ip, "127.0.0.1", "ip address"); DEFINE_int32(port, 8080, "port"); DEFINE_double(retry_ratio,0.5,"retry connect"); DEFINE_bool(daemon,false,"daemon flag"); int main(int argc,char* argv[]) { gflags::SetVersionString("1.0.0"); string usage_str = "Usage: "; usage_str+=argv[0]; gflags::SetUsageMessage(usage_str); if(argc<2){ gflags::ShowUsageWithFlagsRestrict(argv[0], "gflags_test"); return 0; } gflags::ParseCommandLineFlags(&argc, &argv, true); cout<<"ip:"<<FLAGS_ip<<endl; cout<<"port:"<<FLAGS_port<<endl; cout<<"retry_ratio:"<<FLAGS_retry_ratio<<endl; cout<<"daemon:"<<FLAGS_daemon<<endl; return 0; }
转载请注明原文地址: https://www.6miu.com/read-58790.html

最新回复(0)