如何知道命令行中是否提供了 gflag
How to know if a gflag was provided in the command line
我在 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;
}
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 检查输入是否不是整数或数字
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 此代码是否违反一个定义规则
- 是否需要删除包含对象的"pair"?
- 是否可以从int转换为enum类类型
- 无论条件是否为true,if总是在c++中执行
- 如何找到大小'x'数组是否完全填充,在C++?
- 检查值是否在集合p1和p2中,但不在p3中
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 检查 std::shared_ptr<> 的当前底层类型是否为 T
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- C/C++预处理器是否可以检测一些编译器选项
- 如何知道命令行中是否提供了 gflag