gflags 是 google 开源的用于处理命令行参数的项目。使用c++开发,具备python接口。
项目地址:https://github.com/gflags/gflags
gflagsgit clone https://github.com/gflags/gflagscd gflags # 进入项目文件夹
cmake . # 使用 cmake 编译生成 Makefile 文件
make -j 24 # make 编译
sudo make install # 安装库gflags 头文件#include <gflags/gflags.h>DEFINE_string(变量名,默认值,描述);DEFINE_string 只是其中一种类型,其他类型还有:
gflags::ParseCommandLineFlags(&argc, &argv, true);std::cout << "MYSTR is: " << FLAGS_mystr << endl;FLAGS_ + DEFINE_string 中申明的变量名即可调用
➜ g++ gflags_test.cc -o gflags_test -lgflags -lpthread #-l 链接库进行编译
➜ ./gflags_test -mystr="this is a value of gflags' member " # 使用
MYSTR is: this is a value of gflags' member # 输出➜ ./gflags_test -debug_bool # 这样就是 true
➜ ./gflags_test -debug_bool=true # 这样也是 true
➜ ./gflags_test -debug_bool=1 # 这样也是 true
➜ ./gflags_test -debug_bool=false # 0是false#include <iostream>
#include <gflags/gflags.h>
DEFINE_string(name, "zhang san", "your name");
DEFINE_int32(age, 18, "your age");
int main(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
std::cout << "your name is : " << FLAGS_name
<< ", your age is: " << FLAGS_name << std::endl;
return 0;
}如果你想要访问在另一个文件定义的 gflags 变量呢?使用 DECLARE_,它的作用就相当于用 extern 声明变量。为了方便的管理变量,我们推荐在 .cc 或者 .cpp文件中DEFINE 变量,然后只在对应.h 中或者单元测试中 DECLARE 变量。
例如,在foo.cc 定义了一个 gflags 变量 DEFINE_string(name, 'bob', ''),假如你需要在其他文件中使用该变量,那么在 foo.h 中声明 DECLARE_string(name),然后在使用该变量的文件中 include "foo.h" 就可以。当然,这只是为了更好地管理文件关联,如果你不想遵循也是可以的。
使用方法如下:
static bool ValidatePort(const char* flagname, int32 value) {
if (value > 0 && value < 200)
return true;
printf("Invalid value for --%s: %d\n", flagname, (int)value);
return false;
}DEFINE下定义DEFINE_int32(age, 18, "your age");
static const bool port_dummy = gflags::RegisterFlagValidator(&FLAGS_port, &ValidatePort);--name="zhangsan" --age=18➜ ./gflags_test --flagfile user.flags