Search code examples
c++getopt

Playing around with getopt


Hi i'm pretty new to coding and trying to find why this getopt is not working. my compiler complains about "i:o:"

Error C2664 'int getopt(int,char **,char *)': cannot convert argument 3 from 'const char [5]' to 'char *'

int main(int argc, char *argv[])
{
    int opt;
    while ((opt = getopt(argc, argv, "i:o:")) != -1)
    {
        switch (opt)
        {
        case 'i':
            printf("Input file: \"%s\"\n", optarg);
            break;
        case 'o':
            printf("Output file: \"%s\"\n", optarg);
            break;
        }
    }
    return 0;
}    

which is weird since when i was reading about getopt i saw this "The options argument is a string that specifies the option characters that are valid for this program."


Solution

  • According to your error message the getopt function requires a writable options string. You could do that by making a non-const character array like this:

    int main(int argc, char *argv[])
    {
        // non-const char array
        char opts[] = "i:o:"; // copy a string literal in
    
        int opt;
        while ((opt = getopt(argc, argv, opts)) != -1)
        {
            switch (opt)
            {
            case 'i':
                printf("Input file: \"%s\"\n", optarg);
                break;
            case 'o':
                printf("Output file: \"%s\"\n", optarg);
                break;
            }
        }
        return 0;
    }
    

    your original code works fine for me on Linux with GCC v7. It appears the function signature for the version you are using is different.

    On my system it is:

    int getopt (int argc, char** argv, const char* options);
    

    But on your system it appears to be:

    int getopt(int,char **,char *);
    

    That lack of const on the last argument is causing the error which is why you need to give it a non-const string.

    Note: I would not recommend using const_cast for this as some may be tempted. You never know how the function is implemented or if that internal implementation may change at some point.