关于getopt_long的疑惑

来源:互联网 发布:在手机淘宝上购物流程 编辑:程序博客网 时间:2024/05/22 12:58

下面是一个简单的解析命令行参数的程序,但是如果把

static const char *const shortOpts = "ho:v";
static const struct option longOpts[] = {

这两个static去掉的话输入name -h 就报 '-h' 是无效的选项,但是我明明加入了这个选项的

加上static的意思就使短选项和长选项的生存周期改变了,但是当程序一开始执行的时候这两个选项不是应该已经被放入内存了么?为什么还需要使之为静态的?



#include <getopt.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>


const char *programVersion = "V100.01";


void printUsage(FILE *fout)
{
fprintf(fout, "Usage: [ProgramName] options \n");
fprintf(fout, \
" -h --helpDisplay this usage information.\n"
" -v --versionPrint program version info.\n");


exit(0);
}


void formatProcName(char **argv, char *procName, int size)
{
    const char *p = NULL;
    if ( (p = strrchr(argv[0], '/')) == 0) {
        p = argv[0];
    }else {
        ++p;
    }


    strncpy(procName, p, size - 1);
    procName[size] = '\0';  //ensure null terminated
}


int main(int argc, char *argv[])
{
if (argc == 1) {
printUsage(stdout);
}

char progName[100] = {0};
char *outFile = NULL;


int nextOpt = 0;
static const char *const shortOpts = "ho:v";
static const struct option longOpts[] = {
{"version", 0, NULL, 'v'},
{"output", 1, NULL, 'o'},
{"help", 0, NULL, 'h'},
{NULL, 0, NULL, 0}
};


formatProcName(&argv[0], progName, 100);


do{
nextOpt = getopt_long(argc, argv, shortOpts, longOpts, NULL);
switch(nextOpt){
case 'h':
printUsage(stdout);
case 'o':
outFile = optarg;
break;
case 'v':
printf("%s\n", programVersion);
exit(0);
case '?':
printUsage(stdout);
case -1:
goto here;
default:
exit(-1);
}
}while(nextOpt != -1);


here:
printf("file name is: %s\n", outFile);


return 0;
}