【问题标题】:What is the format of BOOST program options command lines?BOOST 程序选项命令行的格式是什么?
【发布时间】:2013-03-20 01:25:00
【问题描述】:

我有两个开关,'i' 和 'p' 分别代表 IPAddress 和 Port。

命令行的格式是什么?

我试过了:

app -i192.168.1.1 -p12345
app -i 192.168.1.1 -p 12345
app -i=192.168.1.1 -p=12345
app -i='192.168.1.1' -p='12345'
app --IPAddress 192.168.1.1 --Port12345

我的应用程序的 IPAddress 有问题,而 DDD 的故障排除在我为 vm 获取时没有发现。

此外,该应用程序作为守护程序运行,因此我的 IP 地址和端口的 cout 语句将被遗忘,并且由于输出值不是 const char*,因此无法打印到 syslog。

我也计划将程序选项用于其他事情,但我对此有点不知所措。

po::options_description config("Configuration");
        config.add_options()
            ("IPAddress,i","IP Address")
            ("Port,p","Port")
             ;
po::variables_map vm;
        po::store(po::parse_command_line(ac, av, config),
                       vm);

        po::notify(vm);
//...and this is how the values are used

int retval = getaddrinfo((vm["IPAddress"].as< string >()).c_str(),(vm["Port"].as<string>()).c_str(), &hint, &list);

这是一个完整的程序...在“Values”之后没有任何内容打印到控制台:

#include <sstream>
#include <algorithm>
#include <stdlib.h>
#include <iterator>
#include <string>

//Using boost program options to read command line and config file data
#include <boost/program_options.hpp>
using namespace std;
using namespace boost;
namespace po = boost::program_options;

int main (int argc, char *argv[])
{
    po::options_description config("Configuration");
    config.add_options()
                ("IPAddress,i","IP Address")
                ("Port,p","Port")
                 ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, config),vm);
    po::notify(vm);

    cout << "Values\n";

    cout << (vm["IPAddress"].as< string >()).c_str();
    cout << " " << (vm["Port"].as<string>()).c_str();

    return 0;

}

输入的值是否无法打印?


这是 gdb 输出,似乎是演员表问题:

28              string address = (vm["IPAddress"].as< string >()).c_str();
(gdb) n
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_any_cast> >'
  what():  boost::bad_any_cast: failed conversion using boost::any_cast

Program received signal SIGABRT, Aborted.
0x0000003afd835935 in raise () from /lib64/libc.so.6

【问题讨论】:

  • 与其直接在您的守护程序应用程序上工作,为什么不为此构建一个独立的测试用例,以便了解如何单独使用它?
  • 我已经想到了。我认为这是一个很好的方法,因为当前设置有很多复杂的测试。
  • 请贴一些代码
  • @bentaisan:听起来你的调试选项非常有限,所以这可能不是一个好方法......

标签: c++ boost options boost-program-options


【解决方案1】:

BOOST 程序选项支持 Unix 系统中已知的常见命令行风格。 因此,这两个应该工作(他们为我工作)

app -i 192.168.1.1 -p 12345
app --IPAddress=192.168.1.1 --Port=12345

备注:

  • 基本教程的文档是at boost.org(可能你已经知道了)
  • 为此编写一个独立的单元测试当然是一个好建议; boost 还为 C++ 提供了一个易于使用的测试框架

【讨论】:

  • 你能看一下 gdb 的输出并给我一个提示吗?我现在正在网上搜索,但这里有人可能有一个快速的解决方案。似乎他们可能是 rtti 不匹配。可能是因为我正在为 64 位目标编译?
  • 奇怪...你确定真的有这样的参数吗? vm.count("IPAddress") 产生什么?它应该是 1(参数的一个实例)。如果为零,则确实不能将不存在的结果转换为字符串
猜你喜欢
  • 1970-01-01
  • 2013-07-05
  • 2019-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-11
  • 2011-03-27
  • 2011-08-04
相关资源
最近更新 更多