Search code examples
cfileglobal-variablesextern

Is there a conflict with keyword "extern" for a variable which is also defined in the same C file?


If I define a global variable in file1.c and also declare it using 'extern' in the same file, is that an error, or is it acceptable?

file1.c:

extern int x;

int x;

I will also declare it using 'extern' it in another file, where I will be using it.

file2.c:

extern int x;

Is this correct/acceptable?


Solution

  • That is more or less exactly how it is meant to be done.
    The extern does not so much mean "will be defined IN A DIFFERENT FILE THAN THIS", it is more of a "will be defined in one code file, not necessarily this one".
    For bonus points, put the declarations (the lines with extern) into a header and include it into both code files, the one with the definition, i.e. the line without extern and the other one.
    Always only have a single one of the definition line in the total of all code files. This way you avoid a redefinition problem and at the same time make sure not to get the declaration inconsistent across multiple code files. (Think of maintenance of your code, which might make necessary to change the definition and declaration of the variable.)
    That said, try to avoid global variables as much as possible.