gflag是一种用来读取命令行参数的东西,也可以从文件内读取多个命令行参数。
一、gflags的安装:
从https://github.com/gflags/gflags.git上获取gflags源码,然后依次进行输入:
mkdir build //此命令的目的是创建一个文件夹,用于放置cmake出来的结果文件,防止污染gflags源码
cd build
cmake ../ //此命令的目的是生成Makefile文件用于gflags的安装
make
make install
至此,gflags安装完毕,需要记住gflags的include路径和lib路径,在编译代码的时候需要将这两种路径链接进来。
二、编写代码运行gflags
在代码中包含头文件 gflags.h
注意,此时一定不要忘记将main函数加入两个输入参数,argc和argv。
在主函数中,加入gflags的初始化语句:
gflags::ParseCommandLineFlags(&argc, &argv, true);
其中的第三个参数为true时,表示将命令行参数中成功解析的标记从命令行列表中移除;为false时,表示不将其移除,依旧//将其保留在argv数组中;其中标记指的是在gflags程序中定义的参数,并在命令行中传入新的参数的变量.
在代码运行的过程中,可以直接使用FLAG_{name}进行参数的获取。
使用DEFINE_string对字符串进行初始化,可以通过命令行参数对其值进行修改,如果想要引用其他文件中的变量,使用DECLARE_string(变量名)来对其进行extern,然后才能对其进行使用。
如果想要将多个命令行参数写入文件中,一并读进程序中,在运行可执行文件的同时,使用–flagfile=“文件名”来进行调用文件。
C++示例代码:
//Author:cica
//this is a demo of gflags
#include <iostream>
#include <gflags/gflags.h>
using namespace std;
DEFINE_string(confPath, "test.conf", "program configure file.");
DEFINE_int32(port, 1111, "program listen port");
DEFINE_bool(debug, true, "run debug mode");
int main(int argc, char** argv)
{
//gflags::ParseCommandLineFlags(&argc, &argv, false);//这里可以试一下第三个参数是true和false的区别
gflags::ParseCommandLineFlags(&argc, &argv, true);
cout << "argc= " << argc << endl;
for(int i = 0; i<argc; ++i)
cout << "argv[" << i << "]:" << argv[i] << endl;;
cout << "confPath = " << FLAGS_confPath << endl;
cout << "port = " << FLAGS_port << endl;
if (FLAGS_debug) {
cout << "this is a debug mode..." << endl;
}
else {
cout << this is a nodebug mode...." << endl;
}
cout << "oh succuss~~" << endl;
gflags::ShutDownCommandLineFlags();
return 0;
}
编译代码的时候一定要将gflags的include库和lib库链接进去,并加上-pthread -gflags
我的示例代码编译命令为:g++ -std=c++11 example.cpp -o example -I/gflags/build/include -L/gflags/build/lib -lpthread -lgflags
运行时,可以直接将命令行参数加在可执行文件后面。如果想要将多个命令行参数写入文件中一并读进程序中,在运行可执行文件的同时,使用–flagfile=“文件名”来加载gflags文件。
例如我的示例代码运行命令为:./example --flagfile=gflags.conf
因为我的flags.conf中写入内容“–port=90”,所以flags.conf中的内容将example.cpp中的port=1111覆盖,输出内容为:
argc= 1
argv[0]:./example
confPath = test.conf
port = 90
run debug mode…
oh succuss~~
运行可执行文件的同时,可以在可执行文件中使用./example –version,其显示的版本号是在main函数中使用google::SetVersionString(“1.1”);进行定义。
使用可执行文件加上–helpshort,可以显示出所有在主函数中定义的标记。