Difference between File Scope and Global Scope Difference between File Scope and Global Scope c c

Difference between File Scope and Global Scope


A variable with file scope can be accessed by any function or block within a single file. To declare a file scoped variable, simply declare a variable outside of a block (same as a global variable) but use the static keyword.

static int nValue; // file scoped variablefloat fValue; // global variableint main(){    double dValue; // local variable}

File scoped variables act exactly like global variables, except their use is restricted to the file in which they are declared.


It is perhaps clearer to illustrate file (or more precisely, translation unit)-scope vs global scope when there are actually multiple translation units...

Take 2 files (each being it's own translation unit, since they don't include each other)

other.cpp

float global_var = 1.0f;static float static_var = 2.0f;

main.cpp

#include <cstdio>extern float global_var;//extern float static_var; // compilation error - undefined reference to 'static_var'int main(int argc, char** argv){    printf("%f\n", global_var);}

Hence the difference is clear.


A name has file scope if the identifier's declaration appears outside of any block. A name with file scope and internal linkage is visible from the point where it is declared to the end of the translation unit.

Global scope or global namespace scope is the outermost namespace scope of a program, in which objects, functions, types and templates can be defined. A name has global namespace scope if the identifier's declaration appears outside of all blocks, namespaces, and classes.

Example:

static int nValue; // file scoped variablefloat fValue; // global variableint main(){    double dValue; // local variable}

Read more here.