C++のgetoptで「undefined reference to optind」
- 作成日: 2021-12-22
- 更新日: 2023-12-24
- カテゴリ: C++
C++のgetoptで「undefined reference to optind」
C++でgetopt.h
をインクルードしてgetopt()
関数を使おうとしました。
それで↓のようなコードを書きました。
// parse options
static struct option longopts[] = {
{"help", no_argument, 0, 'h'},
{"fname", required_argument, 0, 'f'},
{0},
};
extern int opterr;
extern int optind;
opterr = 0; // ignore error messages
optind = 0; // init index of parse
for (;;) {
int optsindex;
int cur = getopt_long(argc, argv, "hf:", longopts, &optsindex);
if (cur == -1) {
break;
}
switch (cur) {
case 0: /* long option only */ break;
case 'h': /* help */ break;
case 'f': printf("%s\n", optarg); break;
case '?':
default: perror("Unknown option"); break;
}
}
if (argc < optind) {
perror("Failed to parse option");
return 1;
}
コンパイルしてみたところ↓のようなエラーが出ました。
undefined reference to 'optind'
optind
はgetopt
が使うグローバル変数ですが、これの参照が見つからないとあります。
少し考えて↓のようにコードを変更しました。
// parse options
static struct option longopts[] = {
{"help", no_argument, 0, 'h'},
{"fname", required_argument, 0, 'f'},
{0},
};
opterr = 0; // ignore error messages
optind = 0; // init index of parse
for (;;) {
int optsindex;
int cur = getopt_long(argc, argv, "hf:", longopts, &optsindex);
if (cur == -1) {
break;
}
switch (cur) {
case 0: /* long option only */ break;
case 'h': /* help */ break;
case 'f': printf("%s\n", optarg); break;
case '?':
default: perror("Unknown option"); break;
}
}
if (argc < optind) {
perror("Failed to parse option");
return 1;
}
以下の2行を削除しています。
extern int opterr;
extern int optind;
これでエラーが出なくなりました。
おわりに
C++はC言語のスーパーセットと言われますが、実際は細かい仕様の違いが目立ちコードを修正しないといけません。
この記事があなたの参考になれば幸いです。
🦝 < getoptでオプションをパースしよう