Search code examples
cstaticstorage-class-specifier

storage-class specifier static with global data


I'm reading the book C-Primer Plus. Following is the text I would like better understanding -

file - constant.h

/* constant.h -- defines some global constants */
static const double PI = 3.14159;
static const char * MONTHS[12] = 
       {"January", "February", "March", "April", "May", "June", "July", "August", 
        "September", "October", "November", "December"};

file - file1.c

/* file1.c -- use global constants defined elsewhere
#include "constant.h"

file - file2.c

/* file2.c -- use global constants defined elsewhere
#include "constant.h"

If you don't use the keyword static, including constant.h in file1.c and in file2.c would result in each file having a defining declaration of the same identifier, which is not supported by C standard. By making each identifier static external, you actually give each file a separate copy of the data.

Can somebody explain the above to me, so I can understand it better ?


Solution

  • If to remove the storage specifier static like

    /* constant.h -- defines some global constants */
    const double PI = 3.14159;
    const char * MONTHS[12] = 
           {"January", "February", "March", "April", "May", "June", "July", "August", 
            "September", "October", "November", "December"};
    

    then each translation units where the header is included will have the objects PI and MONTHS with the external linkage.

    That is the translation units for the file file1.c and file2.c will have definitions of the above objects with the external linkage.

    Now the linker will not know which definition to select because it will have two definitions of the same names.

    When the storage specifier static is used these declarations with the file scope are not visible outside the translation units. They have the internal linkage. Each translation units will have its own definition of the objects. So there will not be an ambiguity between definitions.