我正在学习getopt和 *getopt_long* 如何工作。一个问题是,当我用gdb一步步运行下面这个简单的程序时,optarg总是0x0。
你知道为什么吗?是gdb的问题吗?
我试图在网上搜索并查看程序的汇编代码,但还没有找到答案。
调试代码表明optarg按预期指向 agv[3](值“16”)。
#include <unistd.h>
#include <getopt.h>
#include <stdio.h>
static struct option options[] =
{
/* name has_arg flag val */
{ "num", 1, NULL, 'n' },
{ NULL , 0, NULL , 0 }
};
int main(int argc, char** argv)
{
int option;
option = getopt_long( argc, argv, "n:", options, NULL );
if (option == 'n') {
printf("%s\n", optarg);
if (optarg == NULL)
printf("optarg == NULL\n");
if (optarg == 0)
printf("optarg == 0\n");
}
return 0;
}
在 gdb 上:
(gdb) run -n 16
Starting program: /home/ducalpha/clang/misc/a.out -n 16
...
16 printf("%s\n", optarg);
(gdb) p optarg
$1 = 0x0
输出:
$ ./a.out -n 16
16