1

I want to accept a optional argument to an option only with the long form of the option.

Assume I define the option -v, --verbose with a optional argument for argp:

static struct argp_option opt_global[] =
{
  { "verbose", 'v' , "level", OPTION_ARG_OPTIONAL,  "Increase or set the verbosity level.", -1},
  ...
}

I now want to accept the optional argument only when given with the long option form.

So

--verbose=4

will accept the 4 as a optional argument for verbose.

But with the short option form, the optional argument should not be accepted:

| Command Line |  Handled as       |
|==============|===================|
| -vv          | -v -v             |
| -vx          | -v -x             |
| -v4          | -v -4             |

And assuming I also have -o file to define a output file:

| Command Line |  Handled as       |
|==============|===================|
| -vo file     | -v -o file        |
| -vofile      | -v -o file        |

Anyway I stiil want the help output to look like this:

  -v, --verbose[=level]      Increase or set the verbosity level.

Is this doable with GNU argp?

From reading the docs and playing around, I would assume "No", but maybe I missed something.

Ralf
  • 1,773
  • 8
  • 17

1 Answers1

0

From the argp docs (emphasis is mine):

int key

The integer key provided by the current option to the option parser. If key has a value that is a printable ASCII character (i.e., isascii (key) is true), it also specifies a short option ‘-char’, where char is the ASCII character with the code key.

In other words, to set an option with no short form use a key that is not an ascii character.

For example, in your case it could be:

/* This is not an ascii value so no short form */
#define OPT_VERBOSE_KEY 500

static struct argp_option opt_global[] =
{
  { "verbose", OPT_VERBOSE_KEY , "level", OPTION_ARG_OPTIONAL,  "Increase or set the verbosity level.", -1},
  ...
}
kaylum
  • 13,833
  • 2
  • 22
  • 31
  • And then I could add `{NULL, 'v', NULL, 0, "....", -1}`, but then I would have two entries in the `--help` output, which I would like to avoid. Sorry, the question was unclear about this (updated). – Ralf Sep 27 '20 at 10:30