clanguage-lawyererrno

Is it required to include <errno.h> to use perror?


I can print the human-readable version of errno using perror like this:

#include <errno.h>
#include <stdio.h>

int main(void) {
    FILE *fp = fopen("file.txt", "r");
    if (fp == NULL) {
        perror("Unable to open file");
        return -1;
    }

    fclose(fp);
    return 0;
}

This also works on my implementation:

#include <stdio.h>

int main(void) {
    FILE *fp = fopen("file.txt", "r");
    if (fp == NULL) {
        perror("Unable to open file");
        return -1;
    }

    fclose(fp);
    return 0;
}

Is using perror without including <errno.h> nonstandard?


Solution

  • Yes, it is allowed to use perror without including errno.h. Section 7.21.10.4p1 of the C standard gives the following synopsis of this function:

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

    Including errno.h is only required to access the errno macro.