我正在尝试使用GNU argp
来解析我的C应用程序的参数。我的应用程序接受可选参数和非可选参数。用法如下:
<prog-name> <file> [-i <input file>] [-o <output-file>]
我的程序如下:
#include <stdio.h>
#include <stdlib.h>
#include <argp.h>
typedef struct {
char* args[2];
int silent,verbose;
char* input_file;
char* output_file;
} args_t;
int main(int argc, char** argv);
static error_t parse_opt(int key, char*arg, struct argp_state* state);
error_t parse_opt(int key, char*arg, struct argp_state* state) {
args_t* args = state->input;
switch (key) {
case 'o':
args->output_file = arg;
break;
case 'i':
args->input_file = arg;
break;
case ARGP_KEY_ARG:
if (state->arg_num >= 2) /* Too many arguments. */
argp_usage(state);
args->input_file = arg;
break;
case ARGP_KEY_END:
if (state->arg_num < 2)/* Not enough arguments. */
argp_usage(state);
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
int main (int argc, char** argv) {
// Resources needed for parameter handling
char* doc = "";
char* args_doc = "ARG1 ARG2";
struct argp_option opts[] = {
{"output", 'o', "out", OPTION_ARG_OPTIONAL, "The output file to produce"},
{"input", 'i', "in", OPTION_ARG_OPTIONAL, "The input file to use"},
};
struct argp argp = {opts, parse_opt, args_doc, doc};
args_t args;
args.silent = 0;
args.verbose = 0;
args.input_file = "";
args.output_file = "";
argp_parse(&argp,argc,argv,0,0,&args);
}
当我运行程序时,我得到分段错误。请考虑该文档不是很好,我无法理解。例如,我不知道如何处理强制性论证。但是,当没有以正确的方式传递参数时,我从未期望像argp_parse
这样的过程会让我发生错误。
我还检查了应用程序出错的gdb
,但它不是parse_opt
,它位于argp_parse
的内部。我究竟做错了什么?三江源
答案 0 :(得分:2)
Argp不知道您的阵列中有多少选项。它要求options数组的最后一个元素全部为零:
struct argp_option opts[] = {
{"output", 'o', "out", OPTION_ARG_OPTIONAL, "The output file to produce"},
{"input", 'i', "in", OPTION_ARG_OPTIONAL, "The input file to use"},
{0}
};