the*_*Sin 29 c build getopt command-line-arguments visual-studio
我试图在Windows下编译一组九个*.c文件(以及九个相关的*.h文件).
该代码最初是在Linux中设计的,用于使用标准GNU-Linux/C库"getopt.h"获取命令行参数.该库不适用于在Windows中构建C代码.
我想忽略我的代码现在所做的事情并提出以下问题.对于那些熟悉这个C库"getopt.h"的人:如果它依赖于POSIX风格的命令行参数,是否可以在Windows中构建和运行我的代码?或者我是否必须重新编写适用于Windows的代码,以不同方式传递输入文件(并放弃"getopt.h"依赖关系)?
bob*_*obo 36
getopt()实际上是一个非常简单的功能.我为它做了一个github要点,这里的代码也在下面
#include <string.h>
#include <stdio.h>
int opterr = 1, /* if error message should be printed */
optind = 1, /* index into parent argv vector */
optopt, /* character checked for validity */
optreset; /* reset getopt */
char *optarg; /* argument associated with option */
#define BADCH (int)'?'
#define BADARG (int)':'
#define EMSG ""
/*
* getopt --
* Parse argc/argv argument vector.
*/
int
getopt(int nargc, char * const nargv[], const char *ostr)
{
static char *place = EMSG; /* option letter processing */
const char *oli; /* option letter list index */
if (optreset || !*place) { /* update scanning pointer */
optreset = 0;
if (optind >= nargc || *(place = nargv[optind]) != '-') {
place = EMSG;
return (-1);
}
if (place[1] && *++place == '-') { /* found "--" */
++optind;
place = EMSG;
return (-1);
}
} /* option letter okay? */
if ((optopt = (int)*place++) == (int)':' ||
!(oli = strchr(ostr, optopt))) {
/*
* if the user didn't specify '-' as an option,
* assume it means -1.
*/
if (optopt == (int)'-')
return (-1);
if (!*place)
++optind;
if (opterr && *ostr != ':')
(void)printf("illegal option -- %c\n", optopt);
return (BADCH);
}
if (*++oli != ':') { /* don't need argument */
optarg = NULL;
if (!*place)
++optind;
}
else { /* need an argument */
if (*place) /* no white space */
optarg = place;
else if (nargc <= ++optind) { /* no arg */
place = EMSG;
if (*ostr == ':')
return (BADARG);
if (opterr)
(void)printf("option requires an argument -- %c\n", optopt);
return (BADCH);
}
else /* white space */
optarg = nargv[optind];
place = EMSG;
++optind;
}
return (optopt); /* dump back option letter */
}
Run Code Online (Sandbox Code Playgroud)
Clo*_*oud 22
你是对的.getopt()是POSIX,而不是Windows,您通常必须重新编写所有命令行参数解析代码.
幸运的是,有一个项目,Xgetopt,适用于Windows/MFC类.
http://www.codeproject.com/Articles/1940/XGetopt-A-Unix-compatible-getopt-for-MFC-and-Win32
如果你可以在你的项目中使用它,它应该为你节省大量的编码,并防止你不得不重做所有的解析.
此外,它还带有一个很好的支持GUI的演示应用程序,您应该会发现它很有帮助.
祝好运!
小智 6
可以使用 MinGW 运行时的代码(Todd C. Miller):
http://sourceforge.net/apps/trac/mingw-w64/browser/trunk/mingw-w64-crt/misc
我用这些文件和 CMake 脚本创建了一个小库(可以生成一个 VS 项目):
https://github.com/alex85k/wingetopt