Gflags Note

本文记录 Google开源的一个命令行flag(区别于参数)库 gflags 笔记

using by bazel

To use gflags within a project which uses Bazel as build tool, add the following lines to your WORKSPACE file (see also Bazel documentation of git_repository):

git_repository(
    name = "com_github_gflags_gflags",
    remote = "https://github.com/gflags/gflags.git",
    tag = "v2.2.2"
)

You can then add @com_github_gflags_gflags//:gflags to the deps section of a cc_binary or cc_library rule, and #include "gflags/gflags.h" to include it in your source code. This uses the shared gflags library with multi-threading enabled. In order to use the single-threaded shared gflags library, use the dependency @com_github_gflags_gflags//:gflags_nothreads instead.

For example, see the following BUILD rule of the gflags/example project:

cc_binary(
    name = "foo",
    srcs = ["main.cc"],
    deps = ["@com_github_gflags_gflags//:gflags"],
)

code example

Here are the types supported:

  • DEFINE_bool: boolean
  • DEFINE_int32: 32-bit integer
  • DEFINE_int64: 64-bit integer
  • DEFINE_uint64: unsigned 64-bit integer
  • DEFINE_double: double
  • DEFINE_string: C++ string
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include "gflags/gflags.h"

DEFINE_bool(verbose, false, "Display program name before message");
DEFINE_string(message, "Hello world!", "Message to print");

static bool IsNonEmptyMessage(const char *flagname, const std::string &value)
{
  return value[0] != '\0';
}
DEFINE_validator(message, &IsNonEmptyMessage);

int main(int argc, char *argv[])
{
  gflags::SetUsageMessage("some usage message");
  gflags::SetVersionString("1.0.0");
  gflags::ParseCommandLineFlags(&argc, &argv, true);
  if (FLAGS_verbose) std::cout << gflags::ProgramInvocationShortName() << ": ";
  std::cout << FLAGS_message << std::endl;
  gflags::ShutDownCommandLineFlags();
  return 0;
}
updatedupdated2022-01-042022-01-04