getopt源码寻找尝试
getopt函数的作用是简单的参数分析,例如
gcc -o main main.c
其中,-o
称之为option
,main
称之为optstring
,main.c
称之为parameter
C语言在头文件unistd.h
中定义了getopt
函数
unistd.h
是C语言中提供对POSIX操作系统API访问功能的头文件的名称。
使用
$ vim /usr/include/unistd.h
对其进行访问
其中有这么一句话:
#ifdef __USE_POSIX2
/* Get definitions and prototypes for functions to process the
arguments in ARGV (ARGC of them, minus the program name) for
options given in OPTS. */
# include <bits/getopt_posix.h>
#endif
可见getopt函数的生命在bits/getopt_posix.h
里面
使用
$ vim /usr/include/bits/getopt_posix.h
对其进行访问
里面的一段内容:
#if defined __USE_POSIX2 && !defined __USE_POSIX_IMPLICITLY \
&& !defined __USE_GNU && !defined _GETOPT_H
/* GNU getopt has more functionality than POSIX getopt. When we are
explicitly conforming to POSIX and not GNU, and getopt.h (which is
not part of POSIX) has not been included, the extra functionality
is disabled. */
# ifdef __REDIRECT
extern int __REDIRECT_NTH (getopt, (int ___argc, char *const *___argv,
const char *__shortopts),
__posix_getopt);
# else
extern int __posix_getopt (int ___argc, char *const *___argv,
const char *__shortopts)
__THROW __nonnull ((2, 3));
# define getopt __posix_getopt
明确说明了:
- 该头文件提供的是posix标准的getopt
- gnu标准的getopt功能更强大
- getopt函数是__posix_getopt函数的另一个名字
接下来,我想查看该函数的源码,毕竟源码更会说话
本来想使用man getopt
命令查看getopt函数的详细定义,但是出来的却是命令行getopt命令的解释
我在最后发现了这么一句话:
扫描二维码关注公众号,回复:
12717389 查看本文章

SEE ALSO
bash(1), tcsh(1), getopt(3)
很显然,getopt(3)
中有我们想要的东西
使用man "getopt(3)"
查看,得到了我们需要的东西
(不知道为什么,getopt(2)提示不存在)
但是,仍然找不到getopt
函数的源码
只好放弃
但是这个文件也给出了一些很有用的东西,包括getopt一族的所有函数以及getopt函数的用法
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int
main(int argc, char *argv[])
{
int flags, opt;
int nsecs, tfnd;
nsecs = 0;
tfnd = 0;
flags = 0;
while ((opt = getopt(argc, argv, "nt:")) != -1)
{
switch (opt)
{
case 'n':
flags = 1;
break;
case 't':
nsecs = atoi(optarg);
tfnd = 1;
break;
default: /* '?' */
fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n",
argv[0]);
exit(EXIT_FAILURE);
}
}
printf("flags=%d; tfnd=%d; nsecs=%d; optind=%d\n",
flags, tfnd, nsecs, optind);
if (optind >= argc)
{
fprintf(stderr, "Expected argument after options\n");
exit(EXIT_FAILURE);
}
printf("name argument = %s\n", argv[optind]);
/* Other code omitted */
exit(EXIT_SUCCESS);
}