gflags是一套命令行参数解析工具,比getopt功能更强大,使用起来更加方便,gflags还支持从环境变量、配置文件读取参数(可用gflags代替配置文件)。
1.安装gflags
$git clone https://github.com/gflags/gflags.git
$cd gflags & mkdir build && cd build
$cmake …
$make && make install
gflags 库会默认安装在 /usr/local/lib/ 下,头文件放在 /usr/local/include/gflags/
2.包含头文件
#include <gflags/gflags.h>
3.使用gflags
#include <iostream>
#include <gflags/gflags.h>
/**
* 定义命令行参数变量
* 默认的主机地址为 127.0.0.1,变量解释为 'the server host'
* 默认的端口为 12306,变量解释为 'the server port'
*/
DEFINE_string(host, "127.0.0.1", "the server host");
DEFINE_int32(port, 12306, "the server port");
int main(int argc, char** argv) {
// 解析命令行参数,一般都放在 main 函数中开始位置
gflags::ParseCommandLineFlags(&argc, &argv, true);
// 访问参数变量,加上 FLAGS_
std::cout << "The server host is: " << FLAGS_host
<< ", the server port is: " << FLAGS_port << std::endl;
return 0;
}
代码里使用定义的变量 FLAGS_varname。
编译:g++ gflags_test.cc -o gflags_test -lgflags -lpthread
./gflags_test -host 10.123.78.90
4.使用其他文件里定义的变量
DECLARE_string(var_name);
在a.cpp文件中DEFINE_string(var_name, value, “var_explantion”);
在a.h文件中DECLARE_string(var_name); 其他用var_name的cpp文件include“a.h”
5.使用flagfile
每次在命令行传递参数麻烦,可以用flags.txt,flags.txt文件内容
–host=10.1.1.1
–port=8077
$./gflags_test --flagfile=flags.txt
6.references
[1] https://blog.csdn.net/jcjc918/article/details/50876613
[2] https://blog.csdn.net/lezardfu/article/details/23753741
[3] http://dreamrunner.org/blog/2014/03/09/gflags-jian-ming-shi-yong/
[4] https://blog.csdn.net/cn_wk/article/details/61198182
[5] https://gflags.github.io/gflags/#download