nlib
misc/nflags/nflags.cpp

nn::nlib::Nflagsを利用して、コマンドラインパーサーを簡単に構築する方法を示します。

Nflagsクラスを利用すると、コマンドライン引数の設定を簡単にC++の変数として利用することができるようになります。 更に、それらの変数はプログラム内に分散して定義することができるので、コマンドラインプログラムのモジュラリティを向上させることができます。

#include "nn/nlib/Nflags.h"
//
// nlib_ns::Nflags is a helper class for developing command line tools.
// you can implement command line options easily with Nflags
//
NLIB_FLAGS_DEFINE_bool(boolswitch, false, "My boolean switch");
NLIB_FLAGS_DEFINE_int32(int32switch, 0, "My int switch");
NLIB_FLAGS_DEFINE_string(stringswitch, "", "My string switch");
char* g_argvbuf[128] = {NULL};
int g_Argc;
char** g_Argv = &g_argvbuf[0];
bool NflagsSampleHelp() {
char args[2][128] = {"mycommand", "--help"};
g_Argv[0] = args[0];
g_Argv[1] = args[1];
g_Argc = 2;
nlib_printf("\nParsing 'mycommand --help'\n");
errno_t e = Nflags::Parse(&g_Argc, &g_Argv);
if (e != 0) {
nlib_printf("PARSE ERROR\n");
return false;
}
// you can access xxxxx by NLIB_FLAGS_xxxxx
// NLIB_FLAGS_help is predefined
if (NLIB_FLAGS_help) {
// --help
Nflags::PrintHelp();
}
return true;
}
bool NflagsSampleCommand() {
char args[6][128] = {"mycommand", "--boolswitch", "--int32switch=12345",
"--stringswitch=Phi,Beta,Kappa", "--", "filename"};
g_Argv[0] = args[0];
g_Argv[1] = args[1];
g_Argv[2] = args[2];
g_Argv[3] = args[3];
g_Argv[4] = args[4];
g_Argv[5] = args[5];
g_Argc = 6;
"\nParsing 'mycommand "
"--boolswitch "
"--int32switch=12345 "
"--stringswitch=Phi,Beta,Kappa "
"-- filename"
"'\n");
errno_t e = Nflags::Parse(&g_Argc, &g_Argv);
if (e != 0) {
nlib_printf("PARSE ERROR\n");
return false;
}
// you can access the variable, which is defined by NLIB_FLAGS_DEFINE_xxxx(yyyy, ...),
// by NLIB_FLAGS_yyyy.
// if compilation unit is different,
// you declare NLIB_FLAGS_DECLARE_xxxx(yyyy), and you can use NLIB_FLAGS_yyyy.
nlib_printf("boolswitch: %s\n", NLIB_FLAGS_boolswitch ? "true" : "false");
nlib_printf("int32switch: %d\n", NLIB_FLAGS_int32switch);
nlib_printf("stringswitch: %s\n", NLIB_FLAGS_stringswitch);
// a string list with comma can be splitted by Nflags::GetStringCommaList()
// the arguments which became the options are removed from argv, argc.
// you can use the rest of them without Nflags
nlib_printf("g_Argc after parsing: %d\n", g_Argc);
for (int i = 0; i < g_Argc; ++i) {
nlib_printf("g_Argv[%d] = '%s'\n", i, g_Argv[i]);
}
return true;
}
bool SampleMain(int, char**) { return NflagsSampleHelp() && NflagsSampleCommand(); }
NLIB_MAINFUNC