首页 > optind参数在printf中的输出和gdb中p的值不一样

optind参数在printf中的输出和gdb中p的值不一样

问题描述

今天在看getopt_long()的使用时,对optind的不是很理解,就gdb看了一下函数是怎么走的,结果发现,每一次调用getopt_long()后的optind都是1,但是,printf的时候却不是1,下面附有gdb内容和代码。

疑惑

为什么值会不一样,是optind变量的问题,还是gdb的问题?

附加信息

23      if (optind < argc) {
(gdb) 
26          printf("optind>=argc:%d %d\n", optind, argc);
(gdb) 
optind>=argc:3 3
29      return 0;
(gdb) p optind
$1 = 1
(gdb) p argc
$2 = 3
#include <stdio.h>
#include <string.h>
#include <getopt.h>
#include <errno.h>

int main(int argc, char *argv[]) {
    struct option longopts[] = { 
        { "testa",   no_argument, 0, 'a' },
        { "testb",  no_argument, 0, 'b' },
        { 0, 0, 0, 0 } 
    };  

    // parse command-line options
    int opt;
    while ((opt = getopt_long(argc, argv, "ab", longopts, NULL)) != -1) {
        switch(opt) {
            case 'a': printf("a\n"); break;
            case 'b': printf("b\n"); break;
            case '?':
            default : fprintf(stderr, "%s: option '%c' is invalid\n", argv[0], optopt); break;
        }   
    }   
    if (optind < argc) {
        printf("optind<argc:%d %d\n", optind, argc);
    } else {
        printf("optind>=argc:%d %d\n", optind, argc);
    }   

    return 0;
}


调用getopt_long()后的optind都是1,但是,printf的时候却不是

【热门文章】
【热门文章】