I have tried to read up on the subject but when I try to run what I thought would be the correct thing it doesn't do what I want it to :)
I have a main program, that should take three mandatory arguments, let's call them t, p and s
. Then I have several modules that, as a part of their initialization, also rely on command line arguments. These modules have a command line argument that signals that they are to be used at all.
When I build my string of possible commandline options in my main program I make it look like t:p:s:
and I also loop all the modules and request their "triggering" option character. So the finished string might look like t:p:s:iv
, where i
and v
are triggers for two different modules.
Then in the while loop I do something like this (options is the above mentioned string)
while ((opt = getopt(argc, argv, options)) != -1) {
switch (opt) {
case 't':
break;
case 's':
break;
case 'p':
break;
case 'h':
default:
ShowHelp(this, argc, argv);
exit(EXIT_FAILURE);
}
/*
* Check all available modules and see if options should be passed to it
*/
i = 0;
while((module = this->availablemodules[i++]) != NULL) {
if(opt == module->triggerArg) {
output = module->ParseOptions(module, argc, argv);
AddActiveModule(this, module);
}
}
}
The this->availablemodules
variable is a NULL terminated array of pointers to existing modules. As you can see, I first check for the options used by the main program and then check if given option is a triggering option for a module and in that case I send the arguments to be parsed by that module.
That module might then in turn have a different set of options it takes. So the entered arguments might have looked like this
./myprog -t foo -s bar -p 10 -i -c 2 -v -c 1 -t bar
where the -i
and -v
are module "triggers" and the options after those should be handled in that modules parsing function.
How do I best make this work? And how do I best handle the fact that a modules triggering option might be the same as one of the options needed by the main program (i.e. t:
is used both as an option in the main program and t
is used as a module "trigger")? And is there an ability to force some commands to be mandatory, or do I have to check that manually after parsing all options?
First I constructed the main programs optionstring using the optionstring of every module, but if one module was not to be called that would confuse the system.
I hope everything is clear, but if it's not just ask... I'm a bit confused about how this should be handled so might not explain it very well.
Update: I just read a bit about getopt_long and was thinking, would it be possible to do something like this with that
./myprog -t foo -s bar -p 10 --module=module1 -c 2 --module=module2 -c 1 -t bar
and have module1
and module2
being what identifies the modules to activate instead? Or would it confuse the parser to use --module
several times?