Search code examples
c++boostboost-program-options

Boost program options - pass arg name from function result


I've reproduced my problem based on the example from the official tutorial.

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

namespace po = boost::program_options;
using namespace std;

const char* withAlias(const char* name, const char* alias)
{
    return (string(name) + "," + alias).c_str();
}

int main(int argc, char** argv)
{
    po::options_description desc;
    const auto name = withAlias("compression", "c");
    desc.add_options()
        (name, po::value<int>(), "compression bla bla"); // this doesn't work
        ("compression,c", po::value<int>(), "asdasdasd"); // this works

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

    if (vm.count("compression"))
        cout << "Compression set to " << vm["compression"].as<int>() << endl;
    else
        cout << "Compression not set" << endl;
    return 0;
}

When I run my program: my_bin --compression 5, it throws an error, stating: unrecognized option '--compression'.

When I don't use an alias at all (aka ("compression", ...)), this works as expected.

It happens when there's a , in the name string, but only when it's passed not as a string literal.

Can't really figure out what's causing this.


Solution

  • const char* withAlias(const char* name, const char* alias)
    {
        return (string(name) + "," + alias).c_str();
    }
    

    Your string pointer is invalidated when the std::string object is destroyed.

    You need to keep the std::string around, like so:

    std::string withAlias(std::string name, std::string name)
    {
        return name + "," + alias;
    }
    
    int main(int argc, char** argv)
    {
        po::options_description desc;
        auto name = withAlias("compression", "c");
    
        desc.add_options()
          (name.c_str(), po::value<int>(), "compression bla bla");
        ...