Getopt不包括在内?隐式声明函数'getopt'

Mig*_*ork 15 c linux getopt

我想使用getopt,但它不会起作用.

它给了我

gcc -g -Wall -std=c99 -ftrapv -O2 -Werror -Wshadow -Wundef -save-temps -Werror-implicit-function-declaration   -c -o src/main.o src/main.c
src/main.c: In function ‘main’:
src/main.c:13:2: error: implicit declaration of function ‘getopt’ [-Werror=implicit-function-declaration]
src/main.c:23:14: error: ‘optarg’ undeclared (first use in this function)
src/main.c:23:14: note: each undeclared identifier is reported only once for each function it appears in
src/main.c:26:9: error: ‘optopt’ undeclared (first use in this function)
src/main.c:28:5: error: implicit declaration of function ‘isprint’ [-Werror=implicit-function-declaration]
src/main.c:36:5: error: implicit declaration of function ‘abort’ [-Werror=implicit-function-declaration]
src/main.c:36:5: error: incompatible implicit declaration of built-in function ‘abort’ [-Werror]
src/main.c:43:15: error: ‘optind’ undeclared (first use in this function)
cc1: all warnings being treated as errors
make: *** [src/main.o] Error 1
Run Code Online (Sandbox Code Playgroud)

如果你想看到这里的来源(来自getopt手册页的几乎精确的copypasta)

#include <stdio.h>
#include <unistd.h> // getopt
#include "myfn.h"

int main(int argc, char *argv[])
{

    int aflag = 0;
    int bflag = 0;
    char *cvalue = NULL;
    int c;

    while((c = getopt(argc, argv, "abc:")) != -1) {

        switch(c) {
            case 'a':
                aflag = 1;
                break;
            case 'b':
                bflag = 1;
                break;
            case 'c':
                cvalue = optarg;
                break;
            case '?':
                if (optopt == 'c')
                    fprintf (stderr, "Option -%c requires an argument.\n", optopt);
                else if (isprint(optopt))
                    fprintf (stderr, "Unknown option `-%c'.\n", optopt);
                else
                    fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt);

                return 1;

            default:
                abort ();
        }

    }

    printf ("aflag = %d, bflag = %d, cvalue = %s\n", aflag, bflag, cvalue);

    for (int i = optind; i < argc; i++) {
        printf ("Non-option argument %s\n", argv[i]);
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我有什么想法我做错了吗?

我在Linux上,所以我认为它应该像这样工作.

Gun*_*ica 34

尝试删除-std=c99.这可以防止定义POSIX宏<features.h>,从而阻止<unistd.h>包含<getopt.h>.或者自己包含getopt.h.

  • 没问题.只需在源代码中添加另一个`#include <getopt.h>`. (9认同)
  • @MightyPork你可以尝试`-std = gnu99`而不是`-std = c99 (4认同)
  • `getopt` 是 C 的 GNU 扩展。如果你限制自己使用 ISO C (`-std=c99`),它将不可用。如果可以,请使用`-std=gnu99`,或者手动包含`getopt.h`(注意可移植性问题,因为并非所有平台都提供`getopt.h`) (2认同)