CPP(c++) google gflags

gflags

google开源的gflags是一套命令行参数解析工具,比getopt功能更强大,使用起来更加方便,gflags还支持从环境变量、配置文件读取参数(可用gflags代替配置文件)。参考链接: http://gflags.googlecode.com/svn/trunk/doc/gflags.html

定义flag

#include <iostream>
#include <gflags/gflags.h>

// 定义变量,设置初值,并描述
DEFINE_bool(isvip, false, "If Is VIP"); 
DEFINE_string(ip, "127.0.0.1", "connect ip");
DECLARE_int32(port);
DEFINE_int32(port, 80, "listen port");

int main(int argc, char** argv)
{

  std::string usage("This program does nothing.  Sample usage:\n");
  usage += std::string(argv[0])+" --port 1234 \n or :\n -flagfile=foo.conf";
  google::SetUsageMessage(usage);//可以用来设定usage说明。

  google::ParseCommandLineFlags(&argc, &argv, true);//定义好参数后,最后要告诉执行程序去处理命令行传入的参数
  std::cout<<"ip:"<<FLAGS_ip<<std::endl;  // 访问变量 ip
  std::cout<<"port:"<<FLAGS_port<<std::endl;  // 访问变量 port
  if (FLAGS_isvip)
  {
      std::cout<<"isvip:"<<FLAGS_isvip<<std::endl;  //访问变量 isvip
  }
  google::ShutDownCommandLineFlags();
  return 0;
}

posted @ 2020-01-14 10:21  heimazaifei  阅读(445)  评论(0编辑  收藏  举报