根据这一点,POSIX库不包括getopt.h
。然而,我在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. */
# define __need_getopt
# include <getopt.h>
#endif
这是否意味着getopt.h
在包含unistd.h
时被隐式包含?我的意思是,上面的代码是我应该从unistd头文件的所有实现中得到的东西,还是它只是我特定版本中的东西?此外,__USE_POSIX2
宏是在POSIX.2及以后版本中定义的,还是仅用于POSIX.2?
__USE_POSIX2
是glibc的一个实现细节;它对应于正在定义的CCD_ 7或CCD_。这些也是_GNU_SOURCE
隐含的,除非启用严格的ANSI模式,否则会隐式使用。您不应该直接定义__USE_宏。
由于它对应于值>= 2
,因此它确实适用于以后的版本。有关更多详细信息,请参阅feature_test_macros手册页。
或者,从features.h中的注释(内部标头-不直接包含-负责处理所有这些):
/* These are defined by the user (or the compiler)
to specify the desired environment:
...
_POSIX_C_SOURCE If ==1, like _POSIX_SOURCE; if >=2 add IEEE Std 1003.2;
if >=199309L, add IEEE Std 1003.1b-1993;
if >=199506L, add IEEE Std 1003.1c-1995;
if >=200112L, all of IEEE 1003.1-2004
if >=200809L, all of IEEE 1003.1-2008
_XOPEN_SOURCE Includes POSIX and XPG things. Set to 500 if
Single Unix conformance is wanted, to 600 for the
sixth revision, to 700 for the seventh revision.
getopt(3)
手册页中未提及getopt.h
。如果您需要getopt
,您应该包括unistd.h
并定义(假设为GLIBC)_XOPEN_SOURCE
或_POSIX_C_SOURCE=something_greater_than_2
,而不必担心C库的实现细节。其他环境可能有不同的方式来打开/关闭POSIX功能。
请注意,您的标签暗示使用getopt_long
。这是一个GNU扩展,因此不可移植。