[C++] サードパーティのコマンド ライン解析ライブラリ argparse および cxxopts の導入と使用

argparse ライブラリの紹介

名前は Python のコマンド ライン パラメーター解析ライブラリと同じで、使用方法も似ています。

Github:https://github.com/p-ranav/argparse

argparse は、C++17に基づいたヘッダーのみのコマンド ライン パラメーター解析ライブラリであり、C++17 関連機能に依存しています。

argparse の使用例

#include <argparse/argparse.hpp>

int main(int argc, char *argv[]) {
  argparse::ArgumentParser program("program_name");

  program.add_argument("square")
    .help("display the square of a given integer")
    .scan<'i', int>();

  try {
    program.parse_args(argc, argv);
  }
  catch (const std::exception& err) {
    std::cerr << err.what() << std::endl;
    std::cerr << program;
    return 1;
  }

  auto input = program.get<int>("square");
  std::cout << (input * input) << std::endl;

  return 0;
}

詳しい使用方法については、 https://github.com/p-ranav/argparse/をご覧ください。  

cxxopts ライブラリの紹介

Github:GitHub - jarro2783/cxxopts: 軽量 C++ コマンドライン オプション パーサー

これは軽量の C++ オプション パーサー ライブラリであり、オプションの標準 GNU スタイル構文をサポートしています。

cxxopts はヘッダーのみのコマンド ライン パラメーター解析ツールであり、その値は C++11 の関連機能に依存します。

cxxopts の使用例

#include <cxxopts.hpp>


int main(int argc, char** argv)
{
    cxxopts::Options options("test", "A brief description");

    options.add_options()
        ("b,bar", "Param bar", cxxopts::value<std::string>())
        ("d,debug", "Enable debugging", cxxopts::value<bool>()->default_value("false"))
        ("f,foo", "Param foo", cxxopts::value<std::string>()->implicit_value("implicit")        
        ("h,help", "Print usage")
    ;

    auto result = options.parse(argc, argv);

    if (result.count("help"))
    {
      std::cout << options.help() << std::endl;
      exit(0);
    }
    bool debug = result["debug"].as<bool>();
    std::string bar;
    if (result.count("bar"))
      bar = result["bar"].as<std::string>();
    int foo = result["foo"].as<int>();

    return 0;
}

詳しい使用方法については、 GitHub - jarro2783/cxxopts: Lightweight C++ コマンド ライン オプション パーサーを参照してください。 

おすすめ

転載: blog.csdn.net/u011775793/article/details/135309235