References
- GFlags使用文档, http://www.yeolar.com/note/2014/12/14/gflags/
- How To Use gflags (formerly Google Commandline Flags), https://gflags.github.io/gflags/
Install
- git clone https://github.com/gflags/gflags.git
CMake
Find gflags installation. The gflags_DIR
variable must be set to the <prefix>/lib/cmake/gflags directory containing the gflags-config.cmake file if <prefix> is a non-standard location. Otherwise, CMake should find the gflags installation automatically.
find_package(gflags REQUIRED)
add_executable(foo main.cc) target_link_libraries(foo gflags::gflags)
DEFINE: Defining Flags In Program
Defining a flag is easy: just use the appropriate macro for the type you want the flag to be, as defined at the bottom of gflags/gflags.h
. Here's an example file, foo.cc
:
#include <gflags/gflags.h> DEFINE_bool(big_menu, true, "Include 'advanced' options in the menu listing"); DEFINE_string(languages, "english,french,german", "comma-separated list of languages to offer in the 'lang' menu");
DEFINE_bool
defines a boolean flag. Here are the types supported:
DEFINE_bool
: booleanDEFINE_int32
: 32-bit integerDEFINE_int64
: 64-bit integerDEFINE_uint64
: unsigned 64-bit integerDEFINE_double
: doubleDEFINE_string
: C++ string
Accessing the Flag
All defined flags are available to the program as just a normal variable, with the prefix FLAGS_
prepended. In the above example, the macros define two variables, FLAGS_big_menu
(a bool), and FLAGS_languages
(a C++ string).
You can read and write to the flag just like any other variable:
if (FLAGS_consider_made_up_languages) FLAGS_languages += ",klingon"; // implied by --consider_made_up_languages if (FLAGS_languages.find("finnish") != string::npos) HandleFinnish();
You can also get and set flag values via special functions in gflags.h
. That's a rarer use case, though.
Miscellaneous Notes
If your application has code like this:
#define STRIP_FLAG_HELP 1 // this must go before the #include! #include <gflags/gflags.h>