如果没有直接访问则包含 errno

include errno if not accessed directly

我是否需要包含 errno.h,即使我不直接访问 errno?例如

void *mem = malloc(16384);
if (mem == NULL) {
    perror("malloc");
    exit(EXIT_FAILURE);
}

我尝试了一段像这样的简单代码,但没有包含 errno.h,它成功了,但我不确定是否可以这样做。也许 errho.h 也包含在其他库中,例如 stdlib.h,所以我不需要自己明确包含它?

如果您只使用 perror(),则不需要 <errno.h>

来自Linux程序员手册:

NAME
       perror - print a system error message

SYNOPSIS
       #include <stdio.h>

       void perror(const char *s);

       #include <errno.h>

       const char *sys_errlist[];
       int sys_nerr;
       int errno;

这意味着只有在使用 sys_errlistsys_nerrerrno 时才需要 <errno.h>。请注意 sys_errlistsys_nerr 是 BSD 扩展。

在 C99 标准中也可以找到类似的条目。

7.19.10.4 The perror function

Synopsis

#include <stdio.h>
void perror(const char *s);

并且只有在使用以下内容时才需要 <errno.h>

7.5 Errors

1 The header <errno.h> defines several macros, all relating to the reporting of error conditions.

2 The macros are

EDOM
EILSEQ
ERANGE

which expand to integer constant expressions with type int, distinct positive values, and which are suitable for use in #if preprocessing directives; and

errno

which expands to a modifiable lvalue 175) that has type int, the value of which is set to a positive error number by several library functions.

[...]

4 Additional macro definitions, beginning with E and a digit or E and an uppercase letter, 177) may also be specified by the implementation.

  • malloc() 需要 stdlib.h
  • perror() 需要 stdio.h
  • exit() 需要 stdlib.h

所以这里不需要 errno.h