gflags 定义变量供多个文件使用
使用DECLARE_xxx与DEFINE_xxx方式,DECLARE_xxx在头文件中,DEFINE_xxx在源文件中。
示例:file flags.h

#ifndef FLAGS_H
#define FLAGS_H
#include "gflags/gflags.h"
#include <string>
using std::string;
DECLARE_int32(int32_var);
DECLARE_int64(int64_var);
DECLARE_bool(bool_var);
DECLARE_double(double_var);
DECLARE_uint32(uint32_var);
DECLARE_uint64(uint64_var);
DECLARE_string(string_var);
#endif 

示例:file flags.cpp

#include "flags.h"
DEFINE_int32(int32_var, 0, "int32 变量示例,默认为0");
DEFINE_int64(int64_var, 0, "int64 变量示例,默认为0");
DEFINE_bool(bool_var, true, "bool 变量示例,默认为true");
DEFINE_double(double_var, 0.0, "double 变量示例,默认为0.0");
DEFINE_uint32(uint32_var, 0, "uint32 变量示例,默认为0");
DEFINE_uint64(uint64_var, 0, "uint64 变量示例,默认为0");
DEFINE_string(string_var, "", "string 变量示例,默认为空");

示例使用:

#include "bits/stdc++.h"
#include <gflags/gflags.h>
#include "flags.h"
using namespace std;
int main(int argc, char* argv[])
{
    google::SetVersionString("V1.0.0@const.net.cn");
    google::SetUsageMessage("-help ");
    google::ParseCommandLineFlags(&argc, &argv, true);
    std::cout << FLAGS_string_var<< std::endl;
    std::cout << FLAGS_int32_var<< std::endl;
    std::cout << FLAGS_bool_var<< std::endl;
    return 0;
}

运行结果:

./test_gflags -help
Flags from flags.cpp:
    -bool_var (bool 变量示例,默认为true) type: bool default: true
    -double_var (double 变量示例,默认为0.0) type: double default: 0
    -int32_var (int32 变量示例,默认为0) type: int32 default: 0
    -int64_var (int64 变量示例,默认为0) type: int64 default: 0
    -string_var (string 变量示例,默认为空) type: string default: ""
    -uint32_var (uint32 变量示例,默认为0) type: uint32 default: 0
    -uint64_var (uint64 变量示例,默认为0) type: uint64 default: 0
本文链接地址:https://const.net.cn/559.html

标签: gflags

添加新评论