Search code examples
carraysheader-files

Lifetime of an array in a header file


I want to define an array in a header file, together with the function using it. Not inside the function, but at the top, like a global variable.

Now I am not sure if this will work at all. How long would the array live? Is it like creating a local variable in a loop or will it stay alive since #include "said_header.h" untill the program's end?


Solution

  • Keep in mind that #include "headerfile.h" in C is more or less logically equivalent to opening your text editor and replacing the #include line with the entire contents of the included file.

    So, header files are best used for declarations (which need to be shared between different source files, aka compilation units), while definitions are best kept in just one source file. Note that you can declare an object, and then define it, and indeed doing so when the declaration is in a header file is a good way to allow the compiler to verify that the declaration and the definition match.

    so in headerfile.h you might put the declaration of your array:

    extern char array[100];
    

    and in one of your source files you might define your array:

    #include "headerfile.h"
    char array[100];
    

    and in other source files you can just reference the global array:

    #include "headerfile.h"
    
    strncpy(array, "some string", sizeof(array) - 1);