简体   繁体   中英

Do C getopt and getopt_long only work for main arguments?

the question is pretty clear, I wonder because the man says

The getopt() function parses the command-line arguments.

And I am trying to use it with another function which has the same signature as the main and the argc and argv are obtained with wordexp so everythings seems the same, but when calling getopt I get a segmentation fault immediately after calling getopt_long.

#define   OPT_HELP    'h'
#define   OPTL_HELP   "help"
#define   OPT_MESS    'm'
#define   OPTL_MESS   "message"

#define   OPT_STRING  "hm:"

struct option longopts[] = {
  {OPTL_HELP,     no_argument, 0, OPT_HELP},
  {OPTL_MESS,     required_argument, 0, OPT_MESS},
  {0, 0, 0, 0}
};

#define FLAG_MESS 1

void cmd_chat(int argc, char **argv)
{
  int c, indexptr;
  short flag = 0;
  char message[481];
  while ((c = getopt_long(argc, argv, OPT_STRING,
          longopts, &indexptr)) != -1) {
    debug(MAGENTA "cmd_chat", MAGENTA "c value: %d", c);
    switch (c) {
      case OPT_HELP:
        debug(MAGENTA "cmd_chat", MAGENTA "calling help");
        help(argv[0]);
        return;
        break;
      case OPT_MESS:
        flag |= FLAG_MESS;
        strncpy(message, optarg, 481);
        break;
      default:
        usage(argv[0]);
        break;
    }
  }


[...]

It might be that, but if so I wonder why it is like that also why we should pass the argc and argv to getopt ( _long ).

Thank you.

Both getopt() and getopt_long() will work with every proper char ** and int , there is no difference between argv and any other char ** . If you'll pass argv and argc , or their copies from main to your function and call getopt() from there it will work. Show how your function got argc and argv ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM