Question

I have the code below. But when I run it with --debug=2, the debug variable gets value 100. I 'd expect 2... Where is my mistake? Here the code:

  int debug=0;
  int opt;
  struct option longopts[] = {
    { "debug",    required_argument, &debug, 'd' }
  };
  while ((opt = getopt_long(argc, argv, "d", longopts, NULL))!= -1)
  {
    switch (opt)
    {
      case 'd':
        switch (debug)
        {
          case 1:
            logPrio = LOG_INFO;
            printf("1");
            break;
          case 2:
            printf("2");
            logPrio = LOG_CRIT;
            break;
        }    
    }
  }
 printf ("--%d--", debug);
Was it helpful?

Solution

Specifying &debug in longopts doesn't store the integer value of the option to the specified address, getopt_long expects you to extract integer values yourself.

According to the manual, the int *flag member of struct option does something completely different:

flag "specifies how results are returned for a long option. [If non-NULL], getopt_long() returns 0, and flag points to a variable which is set to val if the option is found, but left unchanged if the option is not found.

You specify &debug for flag and 'd' for val, so debug gets set to 'd' (the number 100) when --debug is specified. Since you're already storing the result of getopt_long into the opt variable, you don't need to store &debug in longopts at all. Instead, use the optarg variable to get the argument to --debug:

  case 'd':
    debug = atoi(optarg);
    switch (debug) {
      ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top