2022/07/19(火) [n年前の日記]
#1 [prog] cmdline.hを少し試用
C++で書いたコマンドラインツールに、コマンドラインオプションを渡して、処理が変わるようにしたい。昨日、getopt() や getopt_long() を使って試してみたけど、それらは記述が面倒だなと…。ヘルプメッセージは自分で用意しないといけないし。
もっと便利なライブラリは無いのかなとググったら、cmdline.h というライブラリがあることを知った。ヘッダーファイル1つを inlcude するだけで使えるらしい。
_C++向け簡易コマンドラインパーザ cmdline - 純粋関数型雑記帳
_tanakh/cmdline: A Command Line Parser
_C++版のgetopt - Qiita
興味が湧いたので、手元で動作確認。動作確認環境は、Windows10 x64 21H2 + MSYS2 + MinGW64 + g++ 12.1.0。
_getopt_sample2.cpp
コンパイルは以下。
実行。
記述量も少なくて済むし、ヘルプメッセージも自動生成してくれるし、ヘッダファイル1つだから使うのも楽だし、静的リンクもしやすい。これは便利だなと…。
もっと便利なライブラリは無いのかなとググったら、cmdline.h というライブラリがあることを知った。ヘッダーファイル1つを inlcude するだけで使えるらしい。
_C++向け簡易コマンドラインパーザ cmdline - 純粋関数型雑記帳
_tanakh/cmdline: A Command Line Parser
_C++版のgetopt - Qiita
興味が湧いたので、手元で動作確認。動作確認環境は、Windows10 x64 21H2 + MSYS2 + MinGW64 + g++ 12.1.0。
_getopt_sample2.cpp
#include "cmdline.h"
#include <stdio.h>
#include <iostream>
int main(int argc, char *argv[])
{
// parse options
cmdline::parser a;
a.add<std::string>("input", 'i', "Input png image", true, "");
a.add<std::string>("output", 'o', "Output png image", true, "");
a.add<std::string>("palette", 'p', "Palette (.png or .gpl)", false, "");
a.add<int>("dither", 'd', "Dither map 2/4/8 (2x2/4x4/8x8)", false, 4);
a.parse_check(argc, argv);
// get options
auto infile = a.get<std::string>("input").c_str();
auto outfile = a.get<std::string>("output").c_str();
auto palette = a.get<std::string>("palette").c_str();
auto dither = a.get<int>("dither");
if (0)
{
std::cout << "input : " << infile << std::endl;
std::cout << "output : " << outfile << std::endl;
std::cout << "palette : " << palette << std::endl;
std::cout << "dither : " << dither << std::endl;
}
else
{
printf("input : [%s]\n", infile);
printf("output : [%s]\n", outfile);
printf("palette : [%s]\n", palette);
printf("dither : %d\n", dither);
}
if (strlen(infile) == 0 || strlen(outfile) == 0)
{
// Not set infile or outfile
printf("%s\n", a.usage().c_str());
return 1;
}
if (strlen(palette) == 0)
{
// Not set palette
printf("Use default palette\n");
}
if (!(dither == 2 || dither == 4 || dither == 8))
{
printf("Error : Unknown dither mode = %d\n\n", dither);
printf("%s\n", a.usage().c_str());
return 1;
}
return 0;
}
コンパイルは以下。
g++ getopt_sample2.cpp -o getopt_sample2.exe -static -lstdc++ -lgcc -lwinpthread -lm
実行。
$ ./getopt_sample2.exe --help usage: D:\...\getopt_sample2.exe --input=string --output=string [options] ... options: -i, --input Input png image (string) -o, --output Output png image (string) -p, --palette Palette (.png or .gpl) (string [=]) -d, --dither Dither map 2/4/8 (2x2/4x4/8x8) (int [=4]) -?, --help print this message $ ./getopt_sample2.exe -i in.png -o out.png -d 8 input : [in.png] output : [out.png] palette : [] dither : 8 Use default palette $ ./getopt_sample2.exe --input in.png --output out.png --dither 8 input : [in.png] output : [out.png] palette : [] dither : 8 Use default palette
記述量も少なくて済むし、ヘルプメッセージも自動生成してくれるし、ヘッダファイル1つだから使うのも楽だし、静的リンクもしやすい。これは便利だなと…。
[ ツッコむ ]
以上です。