getoptと *getopt_long* の仕組みを学んでいます。1 つの問題は、gdbを使用して次の単純なプログラムを段階的に実行すると、optarg が常に 0x0 になることです。
理由はわかりますか?それはgdbの問題ですか?
Web を検索してプログラムのアセンブリ コードを調べようとしましたが、まだ答えが見つかりませんでした。
デバッグ コードは、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