12

The code below I'm using Posix C:

while ((opt = getopt(argc, argv, "a:p:h")) != -1)

How can I port this code to Windows C++ using an alternative function?

Thanks

beaudetious
  • 2,354
  • 3
  • 36
  • 60
  • if someone is looking for something which works on both platforms, you could use something like [cargs](https://github.com/likle/cargs). – likle Aug 02 '20 at 11:20

2 Answers2

10

Microsoft has provided a nice implementation (as well as some other helpers) inside the open source IoTivity project here you could possibly re-use (pending any licensing requirements you may have):

Take a look at the "src" and "include" directories here for "getopt.h/.c".

https://github.com/iotivity/iotivity/tree/master/resource/c_common/windows

Joey
  • 153
  • 1
  • 8
-5

If you had searched you would have found another thread that goes over some compatibility libraries for getopt, among other implementations, for Windows based systems.

getopt.h: Compiling Linux C-Code in Windows

On another note, you could always use the va_arg, va_list, va_start, and va_end functions to process arguments as well.

/* va_arg example */
#include <stdio.h>      /* printf */
#include <stdarg.h>     /* va_list, va_start, va_arg, va_end */

int FindMax (int n, ...)
{
  int i,val,largest;
  va_list vl;
  va_start(vl,n);
  largest=va_arg(vl,int);
  for (i=1;i<n;i++)
  {
    val=va_arg(vl,int);
    largest=(largest>val)?largest:val;
  }
  va_end(vl);
  return largest;
}

int main ()
{
  int m;
  m= FindMax (7,702,422,631,834,892,104,772);
  printf ("The largest value is: %d\n",m);
  return 0;
}

Reference: http://www.cplusplus.com/reference/cstdarg/va_list/

Community
  • 1
  • 1
woahguy
  • 261
  • 3
  • 13
  • 4
    getopt is for interpreting text arguments stored in a single pointer array most likely to parse command line arguments. variadic functions are not similar or compatible. I think the OP was looking for a similar function already in some windows DLL where they could write a small glue function to adapt existing code rather than reimplement getopt. – user2957811 Feb 20 '20 at 19:04