前段时间公司开发使用glags比较多,在此对其做一下总结,方便后续使用。
gflags主要功能:一把向program传进参数的利器。
这点和cpp中定义和使用全局变量的方式很类似:cpp中定义它的default值,hpp中声明以便在其他cpp中使用。
比如:
// foo.h #include "gflags/gflags.h" DECLARE_int32(test_int); // foo.cpp DEFINE_int32(test_int, 1, "test int"); // main.cpp #include "foo.h" int main(int argc, char *argv[]) { google::ParseCommandLineFlags(&argc, &argv, true); // do something with FLAGS_test_int }
(1)bool类型:--noflags_name
// main.cpp DEFINE_bool(test_boolean, true, "test boolean"); // run ./main --notest_boolean
(2)非bool类型:--flag_name=value
gflags提供了一个接口注册一个函数校验值的有效性,这个函数会在2中情况下被调用:
1. 程序启动的时候:此时如果传入的值不对,那么就直接退出;
2. SetCommandLineOption也会引起调用,这个函数是从新设置value的值;
// foo.h #ifndef __FOO_H_ #define __FOO_H_ #include "gflags/gflags.h" DECLARE_int32(test_int); #endif //__FOO_H_ // foo.cpp #include <iostream> #include "foo.h" using std::cerr; using std::endl; using std::cout; using google::int32; DEFINE_int32(test_int, 1, "test int"); static bool valid_test_int_func(const char *flag_name, int32 value) { if (value < 0 || value > 10) { cerr << "invalid value " << value << " for " << flag_name << endl; return false; } cout << "change value " << value << " for " << flag_name << endl; return true; } static const bool test_int_dummy = google::RegisterFlagValidator(&FLAGS_test_int, &valid_test_int_func); // main.cpp #include <iostream> #include "gflags/gflags.h" #include "foo.h" using namespace std; int main(int argc, char *argv[]) { google::ParseCommandLineFlags(&argc, &argv, true); google::SetCommandLineOption("test_int", "13");
cout << FLAGS_test_int << endl; return 0; }
$ ./output/bin/test_gflags --test_int=99
invalid value 99 for test_int
change value 8 for test_int
ERROR: failed validation of new value ‘99‘ for flag ‘test_int‘
$ ./output/bin/test_gflags --test_int=8
change value 8 for test_int
change value 8 for test_int
invalid value 13 for test_int
8
这里重点介绍--flagfile,直接从配置文件读取flags
// flags.conf --test_int=7 ./output/bin/test_gflags --flagfile=./test/flags change value 7 for test_int change value 7 for test_int invalid value 13 for test_int 7
更多gflags相关内容访问:https://gflags.googlecode.com/git-history/master/doc/gflags.html
原文:http://www.cnblogs.com/shadowgao/p/4889946.html