【问题标题】:How to know if a gflag was provided in the command line如何知道命令行中是否提供了 gflag
【发布时间】:2019-01-21 18:09:53
【问题描述】:

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

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

这个标志有一个默认值,所以用户可以选择不在命令行上提供相同的值。 gFlags 中是否有任何 API 可以知道是否在命令行中提供了标志?我没有找到任何东西,所以使用以下 hack:

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;
}

【问题讨论】:

    标签: c++ gflags


    【解决方案1】:

    在详细研究了gflags code之后,我发现了一个返回CommandLineFlagInfo的APIgflags::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;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-14
      • 2016-08-16
      • 2011-08-22
      • 1970-01-01
      • 2020-12-28
      • 1970-01-01
      • 2015-05-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多