2

I use gFlags in a c++ application, to collect command line flags:

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

This flag has a default value, so the user may choose not to provide the same on the command line. Is there any API in gFlags to know if the flag was supplied in the command line? I did not find any, so using the following 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;
}
Curious
  • 2,783
  • 3
  • 29
  • 45

1 Answers1

5

After studying the gflags code in detail, I found an API gflags::GetCommandLineFlagInfoOrDie(const char* name) which returns CommandLineFlagInfo, which contains a boolean flag named is_default which is false if the flag was provided in the command line:

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

So I do not need the hack any more:

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;
}
Curious
  • 2,783
  • 3
  • 29
  • 45