gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:24:03 25 4
gpt4 key购买 nike

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

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

最佳答案

研究完gflags code详细来说,我发现了一个 API gflags::GetCommandLineFlagInfoOrDie(const char* name),它返回 CommandLineFlagInfo,其中包含一个名为 is_default 的 bool 标志,其中如果在命令行中提供了该标志,则为 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;
}

关于c++ - 如何知道命令行中是否提供了 gflag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54295618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com