Search code examples
cdeclarationdefinitionexternlinkage

C define const global using extern


I have 2 files, one containing a global const variable and the other containing an extern definition of the variable, does this work, when i compile the files seperately and link the files together?

/* File 1 */
const int itest;
/* File 2 */
extern const int itest = 123;

Solution

  • A proper way to define a variable in one source file and to make it available by name in others is to define it in one source file with:

    const int itest = 123;  // "extern" is optional and is traditionally omitted in a definition.
    

    and to declare it in any source file(s) that use it with:

    extern const int itest; // "extern" should be used here.
    

    General practice is to put the above declaration in a header file and include that header file in any file that uses the variable, including the one that defines it. Reusing one declaration from a header file helps avoid errors in retyping, pasting, or editing. Including the header in the source file that defines the variable allows the compiler to see both during the same compilation and check them for consistency.

    For reasons related to the history of C development and use, const int itest; without extern or an initializer is a special thing called a tentative definition. This is not a definition but can cause a definition to be created, in effect. Some build tools treat definitions created by tentative definitions specially, allowing them to coalesce with other definitions. This means that having const int itest; in one source file and extern const int itest = 123; might or might not generate a linker error, depending on the build tools used and the switches used with them. You usually do not want this feature and should avoid tentative definitions.