gflags Google Commandline Flags
gflags 是google开源的一套命令行参数解析工具,比 getopt 功能更加强大,使用起来更加方便。用在百度Apollo中gflag被广泛的应用在各种全局变量中,例如节点名,变量名等等
如何使用Gflag
1. 声明&定义 配置项
声明格式:DECLARE_xxx(变量名)
utils_gflags.h
#ifndef UTILS_GFLAGS_H_
#define UTILS_GFLAGS_H_
#include "gflags/gflags.h"
DECLARE_string(work_root);
DECLARE_string(assets_path);
// configs
DECLARE_string(name);
DECLARE_string(version);
DECLARE_bool(enable_update);
#endif // UTILS_GFLAGS_H_
定义格式: DEFINE_xxxxx(变量名,默认值,help-string)
- 其中xxxxx是数据类型,如:bool、int32、int64、uint64、double、string
utils_gflags.cc
#include "utils_gflags.h"
DEFINE_string(work_root, "path/root",
"the root path of app");
DEFINE_string(name, "QGC", "software name");
DEFINE_bool(enable_update, false, "enable update time");
DEFINE_bool: boolean ;
DEFINE_int32: 32-bit integer;
DEFINE_int64: 64-bit integer;
DEFINE_uint64: unsigned 64-bit integer;
DEFINE_double: double;
DEFINE_string: C++ string;
2. 设置配置项参数
app_flagfile.txt
# 1. Flags in this file should be
# decleared in utils_gflags.h
# defined in utils_gflags.cc
# 2. To use it, add the following line into your command line arguments or
# already-in-use flagfile:
# --flagfile=path_to/module_flagfile.txt
# 3. To override the flag values, you must set it after this file, as all Flags
# are evaluated strictly in order.
--work_root=""test/path
--name="app_name"
--enable_update=true
3. 引用配置项
#include "utils_gflags.h"
//通过命令行传递参数
google::ParseCommandLineFlags(&argc, &argv, true);
//通过文件配置参数
std::string conf_path = "/conf/app_flagfile.txt";
google::SetCommandLineOption("flagfile", conf_path.c_str());
....
FLAGS_work_root
FLAGS_name
FLAGS_enable_update