在shell中有些命令如ls 等会支持很多option。那么是如何实现的呢?下面提供了一种给函数实现类似多options支持的思路代码。
options.def
DEF_OPTION(height,int,0,"Height of the input,default = 0")
DEF_OPTION(width,int,0,"Width of the input, default = 0 ")
DEF_OPTION(depth,int,3,"Depth of the input, default = 3")
options.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static inline string handle_option_string(const char *arg) { return arg; }
static inline int handle_option_int(const char *arg) { return atoi(arg); }
static inline float handle_option_float(const char *arg) { return atof(arg); }
int do_option(struct options *options, int argc, const char **argv, int i) {
#define DEF_OPTION(NAME,TYPE,DEFAULT,...) \
if (0==strcmp("--" #NAME,argv[i])) options->NAME = handle_option_##TYPE(argv[i+1]);
#include "options.def"
#undef DEF_OPTION
return 2;
}
void option_print_help()
{
printf("Usage: testa