如何知道命令行中是否提供了 gflag

How to know if a gflag was provided in the command line

本文关键字:gflag 是否 何知道 命令行      更新时间:2023-10-16

我在 c++ 应用程序中使用 gFlags 来收集命令行标志:

DEFINE_string("output_dir", ".", "existing directory to dump output");
int main(int argc, char** argv) {
  gflags::ParseCommandLineFlags(argc, argv, true);
  ...
}

此标志具有默认值,因此用户可以选择不在命令行上提供相同的值。gFlags 中是否有任何 API 可以知道该标志是否在命令行中提供?我没有找到任何,所以使用以下技巧:

DEFINE_string("output_dir", ".", "existing directory to dump output");
static bool flag_set = false;
static void CheckFlags(const int argc, char** const argv) {
  for (int i = 0; i < argc; i++) {
    if (string(argv[i]).find("output_dir") != string::npos) {
      flag_set = true;
      break;
    }
  }
}
int main(int argc, char** argv) {
  CheckFlags(argc, argv);
  gflags::ParseCommandLineFlags(argc, argv, true);
  if (flag_set) {
    // blah.. blah.. 
  }
  return 0;
}

在详细研究了 gflags 代码之后,我发现了一个返回 CommandLineFlagInfo 的 API gflags::GetCommandLineFlagInfoOrDie(const char* name),其中包含一个名为 is_default 的布尔标志,如果命令行中提供了该标志,则该标志为 false:

struct CommandLineFlagInfo {
  std::string name; // the name of the flag
  //...
  bool is_default;  // true if the flag has the default value and
                    // has not been set explicitly from the cmdline
                    // or via SetCommandLineOption
  //...
};

所以我不再需要黑客了:

DEFINE_string("output_dir", ".", "existing directory to dump output");
static bool flag_set = false;
int main(int argc, char** argv) {
  CheckFlags(argc, argv);
  gflags::ParseCommandLineFlags(argc, argv, true);
  bool flag_not_set = gflags::GetCommandLineFlagInfoOrDie("output_dir").is_default;
  if (!flag_not_set) {
    // blah.. blah.. 
  }
  return 0;
}