Search code examples
cheaderconventions

Is it good practice to always include the standard headers?


I read an answer on this site explaining why one shouldn't always include all (include-guarded) header files - slows down compilation time, pollutes the global namespace, etc.

But I'd like to ask specifically - is always including standard headers such as <stdlib.h> and <stdio.h> considered good or bad practice?

Why shouldn't I maintain a stdheaders.h file with #includes for all standard headers, and just include it everywhere? I think this might save me bugs where I'm using a function which I forgot to include the standard header for.

Specifically I would like to know what is considered standard practice in C development. Thank you


Solution

  • Best practice is for each source file, whether it is a .c file or .h file, to include only the headers it needs. Doing so not only reduces compilation time but also serves to document the file's functionality.

    Here are a few examples:

    f1.c:

    #include <stdio.h>
    
    void print_int(int i)
    {
        printf("i=%d\n", i);
    }
    

    f2.c:

    #include <stdlib.h>
    
    void *safe_malloc(size_t size)
    {
        void *p = malloc(size); 
        if (!p) exit(1);
        return p;
    }
    

    f3.c:

    int sum(int a, int b)
    {
        return a+b;
    }
    

    The file f1.c only includes stdio.h because it does I/O but no other functions. Similarly, f2.c only includes stdlib.h because it uses functions defined there but does not use any I/O function, and f3.c doesn't include any headers because it doesn't need them.

    If you think you've included unnecessary files, comment them out and compile with all warnings enabled to see which ones declare functions or variables you need.