代码之家  ›  专栏  ›  技术社区  ›  Curious

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

  •  0
  • Curious  · 技术社区  · 7 年前

    我用 gFlags 在C++应用程序中,收集命令行标志:

    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;
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Curious    7 年前

    关于学习 gflags code 在细节上,我发现了一个API gflags::GetCommandLineFlagInfoOrDie(const char* name) 哪些回报 CommandLineFlagInfo ,其中包含一个名为 is_defaul 如果在命令行中提供了标志,则为假:

    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;
    }
    
    推荐文章