linux Getopt未包含-函数“getopt”的隐式声明

zxlwwiss  于 2023-04-11  发布在  Linux
关注(0)|答案(5)|浏览(132)

我想使用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

如果你想看的话,这里是它的源代码(来自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;
}

知道我哪里做错了吗
我在Linux上,所以我认为它应该这样工作。

wfveoks0

wfveoks01#

尝试删除-std=c99。这将禁用GNU扩展,从而防止在<features.h>中定义POSIX宏,这将防止<unistd.h>包含<getopt.h>
或者将标志替换为-std=gnu99
或者包括你自己的getopt.h
getopt()unistd.h的一部分,这是一个GNU扩展。通过设置-std=c99不使用GNU扩展,函数不再声明,您需要显式包含getopt.h

relj7zay

relj7zay2#

您不需要删除-std=c99。而是在开始时添加#define _POSIX_C_SOURCE 2

hiz5n14c

hiz5n14c3#

在包含项中添加#include <getopt.h>

ttvkxqim

ttvkxqim4#

绝对没有必要更改-std或直接包含getopt.h
如果你想使用C99(或任何其他标准化的)语言特性和POSIX函数(如getopt),正确的做法是在包含相应的头文件之前将_POSIX_C_SOURCE定义为正确的版本(例如,200809L)。有关更多细节,请参见feature_test_macros(7)。

7uzetpgm

7uzetpgm5#

我也遇到了同样的问题,解决它的方法是你最有可能用-std=c99编译,但是尝试-std=gnu99,它应该可以工作。

相关问题