Initialization can be explicit or default. Explicit initialization means assigning a value when the variable is defined. Default initialization occurs when a variable is defined outside any function without an explicit initializer, and the compiler automatically sets it to zero (for static and global variables).
Explicit initialization: int count = 10;
Variable Definition
A definition (e.g., int count;) allocates storage for the variable. A variable can be defined only once in a program, and a global variable must be defined in exactly one translation unit. Multiple definitions across files cause linker errors.
However, having a local variable in one file with the same name as a global variable in another file, or having two local variables with the same name in different files, does not cause a conflict. Note that the main function must appear in exactly one source file.
Variable Declaration
To use a global variable defined in annother file (whether in block scope or global scope), you must declare it using the extern keyword. This declaration does not allocate storage.
Important:
- Do not initialize the variable in an
externdeclaration; that would turn it into a definition and likely cause a linker error. - Declarations can appear multiple times.
Example: extern int sharedValue;
Definitions with const
const cannot be applied to non-member functions.
1. By default, a const object has internal linkage, meaning it is local to the file where it is defined. Therefore, defining the same const global variable in multiple files (or one file defines it const and the other does not) does not cause a linker error; each file gets its own independent copy. A conflict only occurs when the same non-const global variable is defined in more than one file.
2. To share a const variable across files, you must use extern both in the definition and in the declaration:
In C (and inherited by C++)
Like const, a static global variable or function prevents name collisions across files by limiting visibility to the current translation unit.
Differances from const:
- A
staticvariable can be modified (unless also declaredconst). - To access a
staticglobal variable from another file, you would need to#includethe.cppfile (not just a header), which duplicates code and increases compile time.
Static functions (functions prefixed with static) share the same benefits:
- They cannot be called from other translation units.
- Other files can define functions with the same name without conflict.