有没有一种标准化的方法来解析 C 中的命令行参数?

Is there a standardized way to parse command line arguments in C?

我正在学习 C 编程语言并尝试用它做一些基本的事情。我面临的问题是如何解析命令行参数。我读 this answer and tried to find the library summary for unistd.h functions int the standard N1570。但不幸的是,它没有在那里定义(据我所知,仅适用于 POSIX 兼容 OS)。

AFAIK Windows 并不是真正的 POSIX 兼容所以类似于我上面提到的答案

#include <unistd.h>

int main(int argc, char *argv[]){
    int opt;
    while((opt = getopt(argc, argv, "ilv") != -1){
        //do some with it
    }
}

不是很便携。

问题:解析命令行参数的唯一标准化和可移植的方法是自己做吗?

Is there a standardized way to parse command line arguments in C?

是的。不是由 C 委员会标准化的,而是由其他人标准化的。最普遍的是 POSIX 和 Utility Conventions and getopt utility. Using GNU Argument Syntax with argp is just fun and cool. There is also commonly used GNUs getopt_long 用于支持 getopt 的长参数。

The only standardized and portable way to parse command line args is to do it yourself?

在 C11 中有标准化的 none 方式来解析命令行。 C11 仅指定主要参数是字符串,但它们的值只是实现定义的:

If the value of argc is greater than zero, the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup. The intent is to supply to the program information determined prior to program startup from elsewhere in the hosted environment.

C 标准没有引入对 "command line" 的抽象,所以由 "command line arguments" 和 "command line arguments parsing" 组成的抽象是没有定义的。我认为引入一种标准化的方式来解析命令行参数超出了 C 标准的范围。

最便携的方法是编写并使用最便携的代码。事实上,最可移植的代码不会使用任何非标准的 C 库,并且 "do it yourself" 在最可移植的 manner.There 中针对所有可能的体系结构和环境毫无意义。如果你只是为了 GNU/Linux,如果你想在一些疯狂的环境中保持便携,我会选择 getopt,如果你只想针对 GNU/Linux 特定的目标,我会选择 argp系统。 getopt 真的很普遍,甚至像 newlib 这样的嵌入式系统库也实现了 getoptgetopt_long。对于其他人,您可以 copy/include 将其他来源的 getopt 代码添加到您的程序中,从而防止没有它的环境。