LoginSignup
2
0

More than 5 years have passed since last update.

boost::program_optionsでは短いオプション名の指定に注意

Last updated at Posted at 2017-01-28

boostを導入しOSに依存しないオプションを使えるようになりました。
凄く小さいところでハマったのでメモします。

ハマリポイント

失敗例
$ ./src/main --help
Allowed options:
  -  [ --help ]         produce help message
  -  [ --greet ] arg    hi
成功例
$ ./src/main --help
Allowed options:
  -a [ --help ]         produce help message
  -b [ --greet ] arg    hi

何が違うのかパット見わからないと思いますが、短いオプション名が消えてしまっています。

原因

add_options()する際に、短いオプション名の前に空白を入れてしまっていたことでした。すなわち、

誤: ("help, a", "produce help message")
     ↓
正: ("help,a", "produce help message")

最終的なソースファイルが以下になります。

#include <iostream>
#include <boost/program_options.hpp>

namespace po = boost::program_options;

int main(int argc, char* argv[]){
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help,a", "produce help message")  // option名にスペースを入れない!
        ("greet,b", po::value<std::string>(), "hi")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        std::cout << desc << std::endl;
        return 0;
    }
    return 0;
}

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0